repo_name
stringclasses
6 values
pr_number
int64
512
78.9k
pr_title
stringlengths
3
144
pr_description
stringlengths
0
30.3k
author
stringlengths
2
21
date_created
timestamp[ns, tz=UTC]
date_merged
timestamp[ns, tz=UTC]
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
17
30.4k
filepath
stringlengths
9
210
before_content
stringlengths
0
112M
after_content
stringlengths
0
112M
label
int64
-1
1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/Compilers/Core/Portable/Symbols/IPropertySymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a property or indexer. /// </summary> /// <remarks> /// This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future. /// </remarks> public interface IPropertySymbol : ISymbol { /// <summary> /// Returns whether the property is really an indexer. /// </summary> bool IsIndexer { get; } /// <summary> /// True if this is a read-only property; that is, a property with no set accessor. /// </summary> bool IsReadOnly { get; } /// <summary> /// True if this is a write-only property; that is, a property with no get accessor. /// </summary> bool IsWriteOnly { get; } /// <summary> /// Returns true if this property is an auto-created WithEvents property that takes place of /// a field member when the field is marked as WithEvents. /// </summary> bool IsWithEvents { get; } /// <summary> /// Returns true if this property returns by reference. /// </summary> bool ReturnsByRef { get; } /// <summary> /// Returns true if this property returns by reference a readonly variable. /// </summary> bool ReturnsByRefReadonly { get; } /// <summary> /// Returns the RefKind of the property. /// </summary> RefKind RefKind { get; } /// <summary> /// The type of the property. /// </summary> ITypeSymbol Type { get; } NullableAnnotation NullableAnnotation { get; } /// <summary> /// The parameters of this property. If this property has no parameters, returns /// an empty list. Parameters are only present on indexers, or on some properties /// imported from a COM interface. /// </summary> ImmutableArray<IParameterSymbol> Parameters { get; } /// <summary> /// The 'get' accessor of the property, or null if the property is write-only. /// </summary> IMethodSymbol? GetMethod { get; } /// <summary> /// The 'set' accessor of the property, or null if the property is read-only. /// </summary> IMethodSymbol? SetMethod { get; } /// <summary> /// The original definition of the property. If the property is constructed from another /// symbol by type substitution, OriginalDefinition gets the original symbol, as it was /// defined in source or metadata. /// </summary> new IPropertySymbol OriginalDefinition { get; } /// <summary> /// Returns the overridden property, or null. /// </summary> IPropertySymbol? OverriddenProperty { get; } /// <summary> /// Returns interface properties explicitly implemented by this property. /// </summary> /// <remarks> /// Properties imported from metadata can explicitly implement more than one property. /// </remarks> ImmutableArray<IPropertySymbol> ExplicitInterfaceImplementations { get; } /// <summary> /// Custom modifiers associated with the ref modifier, or an empty array if there are none. /// </summary> ImmutableArray<CustomModifier> RefCustomModifiers { get; } /// <summary> /// The list of custom modifiers, if any, associated with the type of the property. /// </summary> ImmutableArray<CustomModifier> TypeCustomModifiers { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a property or indexer. /// </summary> /// <remarks> /// This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future. /// </remarks> public interface IPropertySymbol : ISymbol { /// <summary> /// Returns whether the property is really an indexer. /// </summary> bool IsIndexer { get; } /// <summary> /// True if this is a read-only property; that is, a property with no set accessor. /// </summary> bool IsReadOnly { get; } /// <summary> /// True if this is a write-only property; that is, a property with no get accessor. /// </summary> bool IsWriteOnly { get; } /// <summary> /// Returns true if this property is an auto-created WithEvents property that takes place of /// a field member when the field is marked as WithEvents. /// </summary> bool IsWithEvents { get; } /// <summary> /// Returns true if this property returns by reference. /// </summary> bool ReturnsByRef { get; } /// <summary> /// Returns true if this property returns by reference a readonly variable. /// </summary> bool ReturnsByRefReadonly { get; } /// <summary> /// Returns the RefKind of the property. /// </summary> RefKind RefKind { get; } /// <summary> /// The type of the property. /// </summary> ITypeSymbol Type { get; } NullableAnnotation NullableAnnotation { get; } /// <summary> /// The parameters of this property. If this property has no parameters, returns /// an empty list. Parameters are only present on indexers, or on some properties /// imported from a COM interface. /// </summary> ImmutableArray<IParameterSymbol> Parameters { get; } /// <summary> /// The 'get' accessor of the property, or null if the property is write-only. /// </summary> IMethodSymbol? GetMethod { get; } /// <summary> /// The 'set' accessor of the property, or null if the property is read-only. /// </summary> IMethodSymbol? SetMethod { get; } /// <summary> /// The original definition of the property. If the property is constructed from another /// symbol by type substitution, OriginalDefinition gets the original symbol, as it was /// defined in source or metadata. /// </summary> new IPropertySymbol OriginalDefinition { get; } /// <summary> /// Returns the overridden property, or null. /// </summary> IPropertySymbol? OverriddenProperty { get; } /// <summary> /// Returns interface properties explicitly implemented by this property. /// </summary> /// <remarks> /// Properties imported from metadata can explicitly implement more than one property. /// </remarks> ImmutableArray<IPropertySymbol> ExplicitInterfaceImplementations { get; } /// <summary> /// Custom modifiers associated with the ref modifier, or an empty array if there are none. /// </summary> ImmutableArray<CustomModifier> RefCustomModifiers { get; } /// <summary> /// The list of custom modifiers, if any, associated with the type of the property. /// </summary> ImmutableArray<CustomModifier> TypeCustomModifiers { get; } } }
-1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/Compilers/Test/Resources/Core/SymbolsTests/MultiTargeting/Source1Module.netmodule
MZ@ !L!This program cannot be run in DOS mode. $PELq2)L " @@ `@\"O@  H.text  `.reloc @@B"Ht ( *( *0 +*BSJB v4.0.30319l#~PT#Strings#US#GUID,#BlobG%39&P - X - ` 5 -   3<Module>mscorlibC1`1C2`1TSystemObject.ctorSFooSource1Module.netmodule N.f"AuM z\V4     "" "_CorExeMainmscoree.dll% @ 2
MZ@ !L!This program cannot be run in DOS mode. $PELq2)L " @@ `@\"O@  H.text  `.reloc @@B"Ht ( *( *0 +*BSJB v4.0.30319l#~PT#Strings#US#GUID,#BlobG%39&P - X - ` 5 -   3<Module>mscorlibC1`1C2`1TSystemObject.ctorSFooSource1Module.netmodule N.f"AuM z\V4     "" "_CorExeMainmscoree.dll% @ 2
-1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/VisualStudio/IntegrationTest/TestUtilities/InProcess/TextViewWindow_InProc.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Editor.Implementation.Suggestions; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Operations; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Utilities; using OLECMDEXECOPT = Microsoft.VisualStudio.OLE.Interop.OLECMDEXECOPT; using ThreadHelper = Microsoft.VisualStudio.Shell.ThreadHelper; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess { internal abstract class TextViewWindow_InProc : InProcComponent { /// <remarks> /// This method does not wait for async operations before /// querying the editor /// </remarks> public string[] GetCompletionItems() => ExecuteOnActiveView(view => { var broker = GetComponentModelService<ICompletionBroker>(); var sessions = broker.GetSessions(view); if (sessions.Count != 1) { throw new InvalidOperationException($"Expected exactly one session in the completion list, but found {sessions.Count}"); } var selectedCompletionSet = sessions[0].SelectedCompletionSet; return selectedCompletionSet.Completions.Select(c => c.DisplayText).ToArray(); }); /// <remarks> /// This method does not wait for async operations before /// querying the editor /// </remarks> public string GetCurrentCompletionItem() => ExecuteOnActiveView(view => { var broker = GetComponentModelService<ICompletionBroker>(); var sessions = broker.GetSessions(view); if (sessions.Count != 1) { throw new InvalidOperationException($"Expected exactly one session in the completion list, but found {sessions.Count}"); } var selectedCompletionSet = sessions[0].SelectedCompletionSet; return selectedCompletionSet.SelectionStatus.Completion.DisplayText; }); public void ShowLightBulb() { InvokeOnUIThread(cancellationToken => { var shell = GetGlobalService<SVsUIShell, IVsUIShell>(); var cmdGroup = typeof(VSConstants.VSStd2KCmdID).GUID; var cmdExecOpt = OLECMDEXECOPT.OLECMDEXECOPT_DONTPROMPTUSER; const VSConstants.VSStd2KCmdID ECMD_SMARTTASKS = (VSConstants.VSStd2KCmdID)147; var cmdID = ECMD_SMARTTASKS; object? obj = null; shell.PostExecCommand(cmdGroup, (uint)cmdID, (uint)cmdExecOpt, ref obj); }); } public void WaitForLightBulbSession() { ThreadHelper.JoinableTaskFactory.Run(async () => { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); var view = GetActiveTextView(); var broker = GetComponentModel().GetService<ILightBulbBroker>(); await LightBulbHelper.WaitForLightBulbSessionAsync(broker, view); }); } /// <remarks> /// This method does not wait for async operations before /// querying the editor /// </remarks> public bool IsCompletionActive() { if (!HasActiveTextView()) { return false; } return ExecuteOnActiveView(view => { var broker = GetComponentModelService<ICompletionBroker>(); return broker.IsCompletionActive(view); }); } protected abstract ITextBuffer GetBufferContainingCaret(IWpfTextView view); public string[] GetCurrentClassifications() => InvokeOnUIThread(cancellationToken => { IClassifier? classifier = null; try { var textView = GetActiveTextView(); var selectionSpan = textView.Selection.StreamSelectionSpan.SnapshotSpan; if (selectionSpan.Length == 0) { var textStructureNavigatorSelectorService = GetComponentModelService<ITextStructureNavigatorSelectorService>(); selectionSpan = textStructureNavigatorSelectorService .GetTextStructureNavigator(textView.TextBuffer) .GetExtentOfWord(selectionSpan.Start).Span; } var classifierAggregatorService = GetComponentModelService<IViewClassifierAggregatorService>(); classifier = classifierAggregatorService.GetClassifier(textView); var classifiedSpans = classifier.GetClassificationSpans(selectionSpan); return classifiedSpans.Select(x => x.ClassificationType.Classification).ToArray(); } finally { if (classifier is IDisposable classifierDispose) { classifierDispose.Dispose(); } } }); public int GetVisibleColumnCount() { return ExecuteOnActiveView(view => { return (int)Math.Ceiling(view.ViewportWidth / Math.Max(view.FormattedLineSource.ColumnWidth, 1)); }); } public void PlaceCaret( string marker, int charsOffset, int occurrence, bool extendSelection, bool selectBlock) => ExecuteOnActiveView(view => { var dte = GetDTE(); dte.Find.FindWhat = marker; dte.Find.MatchCase = true; dte.Find.MatchInHiddenText = true; dte.Find.Target = EnvDTE.vsFindTarget.vsFindTargetCurrentDocument; dte.Find.Action = EnvDTE.vsFindAction.vsFindActionFind; var originalPosition = GetCaretPosition(); view.Caret.MoveTo(new SnapshotPoint(GetBufferContainingCaret(view).CurrentSnapshot, 0)); if (occurrence > 0) { var result = EnvDTE.vsFindResult.vsFindResultNotFound; for (var i = 0; i < occurrence; i++) { result = dte.Find.Execute(); } if (result != EnvDTE.vsFindResult.vsFindResultFound) { throw new Exception("Occurrence " + occurrence + " of marker '" + marker + "' not found in text: " + view.TextSnapshot.GetText()); } } else { var result = dte.Find.Execute(); if (result != EnvDTE.vsFindResult.vsFindResultFound) { throw new Exception("Marker '" + marker + "' not found in text: " + view.TextSnapshot.GetText()); } } if (charsOffset > 0) { for (var i = 0; i < charsOffset - 1; i++) { view.Caret.MoveToNextCaretPosition(); } view.Selection.Clear(); } if (charsOffset < 0) { // On the first negative charsOffset, move to anchor-point position, as if the user hit the LEFT key view.Caret.MoveTo(new SnapshotPoint(view.TextSnapshot, view.Selection.AnchorPoint.Position.Position)); for (var i = 0; i < -charsOffset - 1; i++) { view.Caret.MoveToPreviousCaretPosition(); } view.Selection.Clear(); } if (extendSelection) { var newPosition = view.Selection.ActivePoint.Position.Position; view.Selection.Select(new VirtualSnapshotPoint(view.TextSnapshot, originalPosition), new VirtualSnapshotPoint(view.TextSnapshot, newPosition)); view.Selection.Mode = selectBlock ? TextSelectionMode.Box : TextSelectionMode.Stream; } }); public int GetCaretPosition() => ExecuteOnActiveView(view => { var subjectBuffer = GetBufferContainingCaret(view); var bufferPosition = view.Caret.Position.BufferPosition; return bufferPosition.Position; }); public int GetCaretColumn() { return ExecuteOnActiveView(view => { var startOfLine = view.Caret.ContainingTextViewLine.Start.Position; var caretVirtualPosition = view.Caret.Position.VirtualBufferPosition; return caretVirtualPosition.Position - startOfLine + caretVirtualPosition.VirtualSpaces; }); } protected T ExecuteOnActiveView<T>(Func<IWpfTextView, T> action) => InvokeOnUIThread(cancellationToken => { var view = GetActiveTextView(); return action(view); }); protected void ExecuteOnActiveView(Action<IWpfTextView> action) => InvokeOnUIThread(GetExecuteOnActionViewCallback(action)); protected Action<CancellationToken> GetExecuteOnActionViewCallback(Action<IWpfTextView> action) => cancellationToken => { var view = GetActiveTextView(); action(view); }; public void InvokeQuickInfo() { ThreadHelper.JoinableTaskFactory.Run(async () => { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); var broker = GetComponentModelService<IAsyncQuickInfoBroker>(); var session = await broker.TriggerQuickInfoAsync(GetActiveTextView()); Contract.ThrowIfNull(session); }); } public string GetQuickInfo() { return ThreadHelper.JoinableTaskFactory.Run(async () => { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); var view = GetActiveTextView(); var broker = GetComponentModelService<IAsyncQuickInfoBroker>(); var session = broker.GetSession(view); // GetSession will not return null if preceded by a call to InvokeQuickInfo Contract.ThrowIfNull(session); using var cts = new CancellationTokenSource(Helper.HangMitigatingTimeout); while (session.State != QuickInfoSessionState.Visible) { cts.Token.ThrowIfCancellationRequested(); await Task.Delay(50, cts.Token).ConfigureAwait(true); } return QuickInfoToStringConverter.GetStringFromBulkContent(session.Content); }); } public void VerifyTags(string tagTypeName, int expectedCount) => ExecuteOnActiveView(view => { var type = WellKnownTagNames.GetTagTypeByName(tagTypeName); bool filterTag(IMappingTagSpan<ITag> tag) { return tag.Tag.GetType().Equals(type); } var service = GetComponentModelService<IViewTagAggregatorFactoryService>(); var aggregator = service.CreateTagAggregator<ITag>(view); var allTags = aggregator.GetTags(new SnapshotSpan(view.TextSnapshot, 0, view.TextSnapshot.Length)); var tags = allTags.Where(filterTag).Cast<IMappingTagSpan<ITag>>(); var actualCount = tags.Count(); if (expectedCount != actualCount) { var tagsTypesString = string.Join(",", allTags.Select(tag => tag.Tag.ToString())); throw new Exception($"Failed to verify {tagTypeName} tags. Expected count: {expectedCount}, Actual count: {actualCount}. All tags: {tagsTypesString}"); } }); public bool IsLightBulbSessionExpanded() => ExecuteOnActiveView(view => { var broker = GetComponentModel().GetService<ILightBulbBroker>(); if (!broker.IsLightBulbSessionActive(view)) { return false; } var session = broker.GetSession(view); if (session == null || !session.IsExpanded) { return false; } return true; }); public string[] GetLightBulbActions() { return ThreadHelper.JoinableTaskFactory.Run(async () => { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); var view = GetActiveTextView(); var broker = GetComponentModel().GetService<ILightBulbBroker>(); return (await GetLightBulbActionsAsync(broker, view)).Select(a => a.DisplayText).ToArray(); }); } private async Task<IEnumerable<ISuggestedAction>> GetLightBulbActionsAsync(ILightBulbBroker broker, IWpfTextView view) { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); if (!broker.IsLightBulbSessionActive(view)) { var bufferType = view.TextBuffer.ContentType.DisplayName; throw new Exception(string.Format("No light bulb session in View! Buffer content type={0}", bufferType)); } var activeSession = broker.GetSession(view); if (activeSession == null || !activeSession.IsExpanded) { var bufferType = view.TextBuffer.ContentType.DisplayName; throw new InvalidOperationException(string.Format("No expanded light bulb session found after View.ShowSmartTag. Buffer content type={0}", bufferType)); } if (activeSession.TryGetSuggestedActionSets(out var actionSets) != QuerySuggestedActionCompletionStatus.Completed) { actionSets = Array.Empty<SuggestedActionSet>(); } return await SelectActionsAsync(actionSets); } public bool ApplyLightBulbAction(string actionName, FixAllScope? fixAllScope, bool blockUntilComplete) { var lightBulbAction = GetLightBulbApplicationAction(actionName, fixAllScope, blockUntilComplete); var task = ThreadHelper.JoinableTaskFactory.RunAsync(async () => { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); var activeTextView = GetActiveTextView(); return await lightBulbAction(activeTextView); }); if (blockUntilComplete) { var result = task.Join(); DismissLightBulbSession(); return result; } return true; } private Func<IWpfTextView, Task<bool>> GetLightBulbApplicationAction(string actionName, FixAllScope? fixAllScope, bool willBlockUntilComplete) { return async view => { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); var broker = GetComponentModel().GetService<ILightBulbBroker>(); var actions = (await GetLightBulbActionsAsync(broker, view)).ToArray(); var action = actions.FirstOrDefault(a => a.DisplayText == actionName); if (action == null) { var sb = new StringBuilder(); foreach (var item in actions) { sb.AppendLine("Actual ISuggestedAction: " + item.DisplayText); } var bufferType = view.TextBuffer.ContentType.DisplayName; throw new InvalidOperationException( string.Format("ISuggestedAction {0} not found. Buffer content type={1}\r\nActions: {2}", actionName, bufferType, sb.ToString())); } if (fixAllScope != null) { if (!action.HasActionSets) { throw new InvalidOperationException($"Suggested action '{action.DisplayText}' does not support FixAllOccurrences."); } var actionSetsForAction = await action.GetActionSetsAsync(CancellationToken.None); var fixAllAction = await GetFixAllSuggestedActionAsync(actionSetsForAction, fixAllScope.Value); if (fixAllAction == null) { throw new InvalidOperationException($"Unable to find FixAll in {fixAllScope.ToString()} code fix for suggested action '{action.DisplayText}'."); } action = fixAllAction; if (willBlockUntilComplete && action is FixAllSuggestedAction fixAllSuggestedAction && fixAllSuggestedAction.CodeAction is FixSomeCodeAction fixSomeCodeAction) { // Ensure the preview changes dialog will not be shown. Since the operation 'willBlockUntilComplete', // the caller would not be able to interact with the preview changes dialog, and the tests would // either timeout or deadlock. fixSomeCodeAction.GetTestAccessor().ShowPreviewChangesDialog = false; } if (string.IsNullOrEmpty(actionName)) { return false; } // Dismiss the lightbulb session as we not invoking the original code fix. broker.DismissSession(view); } action.Invoke(CancellationToken.None); return !(action is SuggestedAction suggestedAction) || suggestedAction.GetTestAccessor().IsApplied; }; } private async Task<IEnumerable<ISuggestedAction>> SelectActionsAsync(IEnumerable<SuggestedActionSet> actionSets) { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); var actions = new List<ISuggestedAction>(); if (actionSets != null) { foreach (var actionSet in actionSets) { if (actionSet.Actions != null) { foreach (var action in actionSet.Actions) { actions.Add(action); var nestedActionSets = await action.GetActionSetsAsync(CancellationToken.None); var nestedActions = await SelectActionsAsync(nestedActionSets); actions.AddRange(nestedActions); } } } } return actions; } private static async Task<FixAllSuggestedAction?> GetFixAllSuggestedActionAsync(IEnumerable<SuggestedActionSet> actionSets, FixAllScope fixAllScope) { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); foreach (var actionSet in actionSets) { foreach (var action in actionSet.Actions) { if (action is FixAllSuggestedAction fixAllSuggestedAction) { var fixAllCodeAction = fixAllSuggestedAction.CodeAction as FixSomeCodeAction; if (fixAllCodeAction?.FixAllState?.Scope == fixAllScope) { return fixAllSuggestedAction; } } if (action.HasActionSets) { var nestedActionSets = await action.GetActionSetsAsync(CancellationToken.None); var fixAllCodeAction = await GetFixAllSuggestedActionAsync(nestedActionSets, fixAllScope); if (fixAllCodeAction != null) { return fixAllCodeAction; } } } } return null; } public void DismissLightBulbSession() => ExecuteOnActiveView(view => { var broker = GetComponentModel().GetService<ILightBulbBroker>(); broker.DismissSession(view); }); public void DismissCompletionSessions() => ExecuteOnActiveView(view => { var broker = GetComponentModel().GetService<ICompletionBroker>(); broker.DismissAllSessions(view); }); protected abstract bool HasActiveTextView(); protected abstract IWpfTextView GetActiveTextView(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Editor.Implementation.Suggestions; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Operations; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Utilities; using OLECMDEXECOPT = Microsoft.VisualStudio.OLE.Interop.OLECMDEXECOPT; using ThreadHelper = Microsoft.VisualStudio.Shell.ThreadHelper; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess { internal abstract class TextViewWindow_InProc : InProcComponent { /// <remarks> /// This method does not wait for async operations before /// querying the editor /// </remarks> public string[] GetCompletionItems() => ExecuteOnActiveView(view => { var broker = GetComponentModelService<ICompletionBroker>(); var sessions = broker.GetSessions(view); if (sessions.Count != 1) { throw new InvalidOperationException($"Expected exactly one session in the completion list, but found {sessions.Count}"); } var selectedCompletionSet = sessions[0].SelectedCompletionSet; return selectedCompletionSet.Completions.Select(c => c.DisplayText).ToArray(); }); /// <remarks> /// This method does not wait for async operations before /// querying the editor /// </remarks> public string GetCurrentCompletionItem() => ExecuteOnActiveView(view => { var broker = GetComponentModelService<ICompletionBroker>(); var sessions = broker.GetSessions(view); if (sessions.Count != 1) { throw new InvalidOperationException($"Expected exactly one session in the completion list, but found {sessions.Count}"); } var selectedCompletionSet = sessions[0].SelectedCompletionSet; return selectedCompletionSet.SelectionStatus.Completion.DisplayText; }); public void ShowLightBulb() { InvokeOnUIThread(cancellationToken => { var shell = GetGlobalService<SVsUIShell, IVsUIShell>(); var cmdGroup = typeof(VSConstants.VSStd2KCmdID).GUID; var cmdExecOpt = OLECMDEXECOPT.OLECMDEXECOPT_DONTPROMPTUSER; const VSConstants.VSStd2KCmdID ECMD_SMARTTASKS = (VSConstants.VSStd2KCmdID)147; var cmdID = ECMD_SMARTTASKS; object? obj = null; shell.PostExecCommand(cmdGroup, (uint)cmdID, (uint)cmdExecOpt, ref obj); }); } public void WaitForLightBulbSession() { ThreadHelper.JoinableTaskFactory.Run(async () => { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); var view = GetActiveTextView(); var broker = GetComponentModel().GetService<ILightBulbBroker>(); await LightBulbHelper.WaitForLightBulbSessionAsync(broker, view); }); } /// <remarks> /// This method does not wait for async operations before /// querying the editor /// </remarks> public bool IsCompletionActive() { if (!HasActiveTextView()) { return false; } return ExecuteOnActiveView(view => { var broker = GetComponentModelService<ICompletionBroker>(); return broker.IsCompletionActive(view); }); } protected abstract ITextBuffer GetBufferContainingCaret(IWpfTextView view); public string[] GetCurrentClassifications() => InvokeOnUIThread(cancellationToken => { IClassifier? classifier = null; try { var textView = GetActiveTextView(); var selectionSpan = textView.Selection.StreamSelectionSpan.SnapshotSpan; if (selectionSpan.Length == 0) { var textStructureNavigatorSelectorService = GetComponentModelService<ITextStructureNavigatorSelectorService>(); selectionSpan = textStructureNavigatorSelectorService .GetTextStructureNavigator(textView.TextBuffer) .GetExtentOfWord(selectionSpan.Start).Span; } var classifierAggregatorService = GetComponentModelService<IViewClassifierAggregatorService>(); classifier = classifierAggregatorService.GetClassifier(textView); var classifiedSpans = classifier.GetClassificationSpans(selectionSpan); return classifiedSpans.Select(x => x.ClassificationType.Classification).ToArray(); } finally { if (classifier is IDisposable classifierDispose) { classifierDispose.Dispose(); } } }); public int GetVisibleColumnCount() { return ExecuteOnActiveView(view => { return (int)Math.Ceiling(view.ViewportWidth / Math.Max(view.FormattedLineSource.ColumnWidth, 1)); }); } public void PlaceCaret( string marker, int charsOffset, int occurrence, bool extendSelection, bool selectBlock) => ExecuteOnActiveView(view => { var dte = GetDTE(); dte.Find.FindWhat = marker; dte.Find.MatchCase = true; dte.Find.MatchInHiddenText = true; dte.Find.Target = EnvDTE.vsFindTarget.vsFindTargetCurrentDocument; dte.Find.Action = EnvDTE.vsFindAction.vsFindActionFind; var originalPosition = GetCaretPosition(); view.Caret.MoveTo(new SnapshotPoint(GetBufferContainingCaret(view).CurrentSnapshot, 0)); if (occurrence > 0) { var result = EnvDTE.vsFindResult.vsFindResultNotFound; for (var i = 0; i < occurrence; i++) { result = dte.Find.Execute(); } if (result != EnvDTE.vsFindResult.vsFindResultFound) { throw new Exception("Occurrence " + occurrence + " of marker '" + marker + "' not found in text: " + view.TextSnapshot.GetText()); } } else { var result = dte.Find.Execute(); if (result != EnvDTE.vsFindResult.vsFindResultFound) { throw new Exception("Marker '" + marker + "' not found in text: " + view.TextSnapshot.GetText()); } } if (charsOffset > 0) { for (var i = 0; i < charsOffset - 1; i++) { view.Caret.MoveToNextCaretPosition(); } view.Selection.Clear(); } if (charsOffset < 0) { // On the first negative charsOffset, move to anchor-point position, as if the user hit the LEFT key view.Caret.MoveTo(new SnapshotPoint(view.TextSnapshot, view.Selection.AnchorPoint.Position.Position)); for (var i = 0; i < -charsOffset - 1; i++) { view.Caret.MoveToPreviousCaretPosition(); } view.Selection.Clear(); } if (extendSelection) { var newPosition = view.Selection.ActivePoint.Position.Position; view.Selection.Select(new VirtualSnapshotPoint(view.TextSnapshot, originalPosition), new VirtualSnapshotPoint(view.TextSnapshot, newPosition)); view.Selection.Mode = selectBlock ? TextSelectionMode.Box : TextSelectionMode.Stream; } }); public int GetCaretPosition() => ExecuteOnActiveView(view => { var subjectBuffer = GetBufferContainingCaret(view); var bufferPosition = view.Caret.Position.BufferPosition; return bufferPosition.Position; }); public int GetCaretColumn() { return ExecuteOnActiveView(view => { var startOfLine = view.Caret.ContainingTextViewLine.Start.Position; var caretVirtualPosition = view.Caret.Position.VirtualBufferPosition; return caretVirtualPosition.Position - startOfLine + caretVirtualPosition.VirtualSpaces; }); } protected T ExecuteOnActiveView<T>(Func<IWpfTextView, T> action) => InvokeOnUIThread(cancellationToken => { var view = GetActiveTextView(); return action(view); }); protected void ExecuteOnActiveView(Action<IWpfTextView> action) => InvokeOnUIThread(GetExecuteOnActionViewCallback(action)); protected Action<CancellationToken> GetExecuteOnActionViewCallback(Action<IWpfTextView> action) => cancellationToken => { var view = GetActiveTextView(); action(view); }; public void InvokeQuickInfo() { ThreadHelper.JoinableTaskFactory.Run(async () => { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); var broker = GetComponentModelService<IAsyncQuickInfoBroker>(); var session = await broker.TriggerQuickInfoAsync(GetActiveTextView()); Contract.ThrowIfNull(session); }); } public string GetQuickInfo() { return ThreadHelper.JoinableTaskFactory.Run(async () => { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); var view = GetActiveTextView(); var broker = GetComponentModelService<IAsyncQuickInfoBroker>(); var session = broker.GetSession(view); // GetSession will not return null if preceded by a call to InvokeQuickInfo Contract.ThrowIfNull(session); using var cts = new CancellationTokenSource(Helper.HangMitigatingTimeout); while (session.State != QuickInfoSessionState.Visible) { cts.Token.ThrowIfCancellationRequested(); await Task.Delay(50, cts.Token).ConfigureAwait(true); } return QuickInfoToStringConverter.GetStringFromBulkContent(session.Content); }); } public void VerifyTags(string tagTypeName, int expectedCount) => ExecuteOnActiveView(view => { var type = WellKnownTagNames.GetTagTypeByName(tagTypeName); bool filterTag(IMappingTagSpan<ITag> tag) { return tag.Tag.GetType().Equals(type); } var service = GetComponentModelService<IViewTagAggregatorFactoryService>(); var aggregator = service.CreateTagAggregator<ITag>(view); var allTags = aggregator.GetTags(new SnapshotSpan(view.TextSnapshot, 0, view.TextSnapshot.Length)); var tags = allTags.Where(filterTag).Cast<IMappingTagSpan<ITag>>(); var actualCount = tags.Count(); if (expectedCount != actualCount) { var tagsTypesString = string.Join(",", allTags.Select(tag => tag.Tag.ToString())); throw new Exception($"Failed to verify {tagTypeName} tags. Expected count: {expectedCount}, Actual count: {actualCount}. All tags: {tagsTypesString}"); } }); public bool IsLightBulbSessionExpanded() => ExecuteOnActiveView(view => { var broker = GetComponentModel().GetService<ILightBulbBroker>(); if (!broker.IsLightBulbSessionActive(view)) { return false; } var session = broker.GetSession(view); if (session == null || !session.IsExpanded) { return false; } return true; }); public string[] GetLightBulbActions() { return ThreadHelper.JoinableTaskFactory.Run(async () => { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); var view = GetActiveTextView(); var broker = GetComponentModel().GetService<ILightBulbBroker>(); return (await GetLightBulbActionsAsync(broker, view)).Select(a => a.DisplayText).ToArray(); }); } private async Task<IEnumerable<ISuggestedAction>> GetLightBulbActionsAsync(ILightBulbBroker broker, IWpfTextView view) { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); if (!broker.IsLightBulbSessionActive(view)) { var bufferType = view.TextBuffer.ContentType.DisplayName; throw new Exception(string.Format("No light bulb session in View! Buffer content type={0}", bufferType)); } var activeSession = broker.GetSession(view); if (activeSession == null || !activeSession.IsExpanded) { var bufferType = view.TextBuffer.ContentType.DisplayName; throw new InvalidOperationException(string.Format("No expanded light bulb session found after View.ShowSmartTag. Buffer content type={0}", bufferType)); } if (activeSession.TryGetSuggestedActionSets(out var actionSets) != QuerySuggestedActionCompletionStatus.Completed) { actionSets = Array.Empty<SuggestedActionSet>(); } return await SelectActionsAsync(actionSets); } public bool ApplyLightBulbAction(string actionName, FixAllScope? fixAllScope, bool blockUntilComplete) { var lightBulbAction = GetLightBulbApplicationAction(actionName, fixAllScope, blockUntilComplete); var task = ThreadHelper.JoinableTaskFactory.RunAsync(async () => { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); var activeTextView = GetActiveTextView(); return await lightBulbAction(activeTextView); }); if (blockUntilComplete) { var result = task.Join(); DismissLightBulbSession(); return result; } return true; } private Func<IWpfTextView, Task<bool>> GetLightBulbApplicationAction(string actionName, FixAllScope? fixAllScope, bool willBlockUntilComplete) { return async view => { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); var broker = GetComponentModel().GetService<ILightBulbBroker>(); var actions = (await GetLightBulbActionsAsync(broker, view)).ToArray(); var action = actions.FirstOrDefault(a => a.DisplayText == actionName); if (action == null) { var sb = new StringBuilder(); foreach (var item in actions) { sb.AppendLine("Actual ISuggestedAction: " + item.DisplayText); } var bufferType = view.TextBuffer.ContentType.DisplayName; throw new InvalidOperationException( string.Format("ISuggestedAction {0} not found. Buffer content type={1}\r\nActions: {2}", actionName, bufferType, sb.ToString())); } if (fixAllScope != null) { if (!action.HasActionSets) { throw new InvalidOperationException($"Suggested action '{action.DisplayText}' does not support FixAllOccurrences."); } var actionSetsForAction = await action.GetActionSetsAsync(CancellationToken.None); var fixAllAction = await GetFixAllSuggestedActionAsync(actionSetsForAction, fixAllScope.Value); if (fixAllAction == null) { throw new InvalidOperationException($"Unable to find FixAll in {fixAllScope.ToString()} code fix for suggested action '{action.DisplayText}'."); } action = fixAllAction; if (willBlockUntilComplete && action is FixAllSuggestedAction fixAllSuggestedAction && fixAllSuggestedAction.CodeAction is FixSomeCodeAction fixSomeCodeAction) { // Ensure the preview changes dialog will not be shown. Since the operation 'willBlockUntilComplete', // the caller would not be able to interact with the preview changes dialog, and the tests would // either timeout or deadlock. fixSomeCodeAction.GetTestAccessor().ShowPreviewChangesDialog = false; } if (string.IsNullOrEmpty(actionName)) { return false; } // Dismiss the lightbulb session as we not invoking the original code fix. broker.DismissSession(view); } action.Invoke(CancellationToken.None); return !(action is SuggestedAction suggestedAction) || suggestedAction.GetTestAccessor().IsApplied; }; } private async Task<IEnumerable<ISuggestedAction>> SelectActionsAsync(IEnumerable<SuggestedActionSet> actionSets) { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); var actions = new List<ISuggestedAction>(); if (actionSets != null) { foreach (var actionSet in actionSets) { if (actionSet.Actions != null) { foreach (var action in actionSet.Actions) { actions.Add(action); var nestedActionSets = await action.GetActionSetsAsync(CancellationToken.None); var nestedActions = await SelectActionsAsync(nestedActionSets); actions.AddRange(nestedActions); } } } } return actions; } private static async Task<FixAllSuggestedAction?> GetFixAllSuggestedActionAsync(IEnumerable<SuggestedActionSet> actionSets, FixAllScope fixAllScope) { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); foreach (var actionSet in actionSets) { foreach (var action in actionSet.Actions) { if (action is FixAllSuggestedAction fixAllSuggestedAction) { var fixAllCodeAction = fixAllSuggestedAction.CodeAction as FixSomeCodeAction; if (fixAllCodeAction?.FixAllState?.Scope == fixAllScope) { return fixAllSuggestedAction; } } if (action.HasActionSets) { var nestedActionSets = await action.GetActionSetsAsync(CancellationToken.None); var fixAllCodeAction = await GetFixAllSuggestedActionAsync(nestedActionSets, fixAllScope); if (fixAllCodeAction != null) { return fixAllCodeAction; } } } } return null; } public void DismissLightBulbSession() => ExecuteOnActiveView(view => { var broker = GetComponentModel().GetService<ILightBulbBroker>(); broker.DismissSession(view); }); public void DismissCompletionSessions() => ExecuteOnActiveView(view => { var broker = GetComponentModel().GetService<ICompletionBroker>(); broker.DismissAllSessions(view); }); protected abstract bool HasActiveTextView(); protected abstract IWpfTextView GetActiveTextView(); } }
-1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/CommonFormattingHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Text; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Utilities { internal static class CommonFormattingHelpers { public static readonly Comparison<SuppressOperation> SuppressOperationComparer = (o1, o2) => { return o1.TextSpan.Start - o2.TextSpan.Start; }; public static readonly Comparison<IndentBlockOperation> IndentBlockOperationComparer = (o1, o2) => { // smaller one goes left var s = o1.TextSpan.Start - o2.TextSpan.Start; if (s != 0) { return s; } // bigger one goes left var e = o2.TextSpan.End - o1.TextSpan.End; if (e != 0) { return e; } return 0; }; public static IEnumerable<ValueTuple<SyntaxToken, SyntaxToken>> ConvertToTokenPairs(this SyntaxNode root, IList<TextSpan> spans) { Contract.ThrowIfNull(root); Contract.ThrowIfFalse(spans.Count > 0); if (spans.Count == 1) { // special case, if there is only one span, return right away yield return root.ConvertToTokenPair(spans[0]); yield break; } var previousOne = root.ConvertToTokenPair(spans[0]); // iterate through each spans and make sure each one doesn't overlap each other for (var i = 1; i < spans.Count; i++) { var currentOne = root.ConvertToTokenPair(spans[i]); if (currentOne.Item1.SpanStart <= previousOne.Item2.Span.End) { // oops, looks like two spans are overlapping each other. merge them previousOne = ValueTuple.Create(previousOne.Item1, previousOne.Item2.Span.End < currentOne.Item2.Span.End ? currentOne.Item2 : previousOne.Item2); continue; } // okay, looks like things are in good shape yield return previousOne; // move to next one previousOne = currentOne; } // give out the last one yield return previousOne; } public static ValueTuple<SyntaxToken, SyntaxToken> ConvertToTokenPair(this SyntaxNode root, TextSpan textSpan) { Contract.ThrowIfNull(root); Contract.ThrowIfTrue(textSpan.IsEmpty); var startToken = root.FindToken(textSpan.Start); // empty token, get previous non-zero length token if (startToken.IsMissing) { // if there is no previous token, startToken will be set to SyntaxKind.None startToken = startToken.GetPreviousToken(); } // span is on leading trivia if (textSpan.Start < startToken.SpanStart) { // if there is no previous token, startToken will be set to SyntaxKind.None startToken = startToken.GetPreviousToken(); } // adjust position where we try to search end token var endToken = (root.FullSpan.End <= textSpan.End) ? root.GetLastToken(includeZeroWidth: true) : root.FindToken(textSpan.End); // empty token, get next token if (endToken.IsMissing) { endToken = endToken.GetNextToken(); } // span is on trailing trivia if (endToken.Span.End < textSpan.End) { endToken = endToken.GetNextToken(); } // make sure tokens are not SyntaxKind.None startToken = (startToken.RawKind != 0) ? startToken : root.GetFirstToken(includeZeroWidth: true); endToken = (endToken.RawKind != 0) ? endToken : root.GetLastToken(includeZeroWidth: true); // token is in right order Contract.ThrowIfFalse(startToken.Equals(endToken) || startToken.Span.End <= endToken.SpanStart); return ValueTuple.Create(startToken, endToken); } public static bool IsInvalidTokenRange(this SyntaxNode root, SyntaxToken startToken, SyntaxToken endToken) { // given token must be token exist excluding EndOfFile token. if (startToken.RawKind == 0 || endToken.RawKind == 0) { return true; } if (startToken.Equals(endToken)) { return false; } // regular case. // start token can't be end of file token and start token must be before end token if it's not the same token. return root.FullSpan.End == startToken.SpanStart || startToken.FullSpan.End > endToken.FullSpan.Start; } public static int GetTokenColumn(this SyntaxTree tree, SyntaxToken token, int tabSize) { Contract.ThrowIfNull(tree); Contract.ThrowIfTrue(token.RawKind == 0); var startPosition = token.SpanStart; var line = tree.GetText().Lines.GetLineFromPosition(startPosition); return line.GetColumnFromLineOffset(startPosition - line.Start, tabSize); } public static string GetText(this SourceText text, SyntaxToken token1, SyntaxToken token2) => (token1.RawKind == 0) ? text.ToString(TextSpan.FromBounds(0, token2.SpanStart)) : text.ToString(TextSpan.FromBounds(token1.Span.End, token2.SpanStart)); public static string GetTextBetween(SyntaxToken token1, SyntaxToken token2) { var builder = new StringBuilder(); AppendTextBetween(token1, token2, builder); return builder.ToString(); } public static void AppendTextBetween(SyntaxToken token1, SyntaxToken token2, StringBuilder builder) { Contract.ThrowIfTrue(token1.RawKind == 0 && token2.RawKind == 0); Contract.ThrowIfTrue(token1.Equals(token2)); if (token1.RawKind == 0) { AppendLeadingTriviaText(token2, builder); return; } if (token2.RawKind == 0) { AppendTrailingTriviaText(token1, builder); return; } if (token1.FullSpan.End == token2.FullSpan.Start) { AppendTextBetweenTwoAdjacentTokens(token1, token2, builder); return; } AppendTrailingTriviaText(token1, builder); for (var token = token1.GetNextToken(includeZeroWidth: true); token.FullSpan.End <= token2.FullSpan.Start; token = token.GetNextToken(includeZeroWidth: true)) { builder.Append(token.ToFullString()); } AppendPartialLeadingTriviaText(token2, builder, token1.TrailingTrivia.FullSpan.End); } private static void AppendTextBetweenTwoAdjacentTokens(SyntaxToken token1, SyntaxToken token2, StringBuilder builder) { AppendTrailingTriviaText(token1, builder); AppendLeadingTriviaText(token2, builder); } private static void AppendLeadingTriviaText(SyntaxToken token, StringBuilder builder) { if (!token.HasLeadingTrivia) { return; } foreach (var trivia in token.LeadingTrivia) { builder.Append(trivia.ToFullString()); } } /// <summary> /// If the token1 is expected to be part of the leading trivia of the token2 then the trivia /// before the token1FullSpanEnd, which the fullspan end of the token1 should be ignored /// </summary> private static void AppendPartialLeadingTriviaText(SyntaxToken token, StringBuilder builder, int token1FullSpanEnd) { if (!token.HasLeadingTrivia) { return; } foreach (var trivia in token.LeadingTrivia) { if (trivia.FullSpan.End <= token1FullSpanEnd) { continue; } builder.Append(trivia.ToFullString()); } } private static void AppendTrailingTriviaText(SyntaxToken token, StringBuilder builder) { if (!token.HasTrailingTrivia) { return; } foreach (var trivia in token.TrailingTrivia) { builder.Append(trivia.ToFullString()); } } /// <summary> /// this will create a span that includes its trailing trivia of its previous token and leading trivia of its next token /// for example, for code such as "class A { int ...", if given tokens are "A" and "{", this will return span [] of "class[ A { ]int ..." /// which included trailing trivia of "class" which is previous token of "A", and leading trivia of "int" which is next token of "{" /// </summary> public static TextSpan GetSpanIncludingTrailingAndLeadingTriviaOfAdjacentTokens(SyntaxToken startToken, SyntaxToken endToken) { // most of cases we can just ask previous and next token to create the span, but in some corner cases such as omitted token case, // those navigation function doesn't work, so we have to explore the tree ourselves to create correct span var startPosition = GetStartPositionOfSpan(startToken); var endPosition = GetEndPositionOfSpan(endToken); return TextSpan.FromBounds(startPosition, endPosition); } private static int GetEndPositionOfSpan(SyntaxToken token) { var nextToken = token.GetNextToken(); if (nextToken.RawKind != 0) { return nextToken.SpanStart; } var backwardPosition = token.FullSpan.End; var parentNode = GetParentThatContainsGivenSpan(token.Parent, backwardPosition, forward: false); if (parentNode == null) { // reached the end of tree return token.FullSpan.End; } Contract.ThrowIfFalse(backwardPosition < parentNode.FullSpan.End); nextToken = parentNode.FindToken(backwardPosition + 1); Contract.ThrowIfTrue(nextToken.RawKind == 0); return nextToken.SpanStart; } public static int GetStartPositionOfSpan(SyntaxToken token) { var previousToken = token.GetPreviousToken(); if (previousToken.RawKind != 0) { return previousToken.Span.End; } // first token in the tree var forwardPosition = token.FullSpan.Start; if (forwardPosition <= 0) { return 0; } var parentNode = GetParentThatContainsGivenSpan(token.Parent, forwardPosition, forward: true); Contract.ThrowIfNull(parentNode); Contract.ThrowIfFalse(parentNode.FullSpan.Start < forwardPosition); previousToken = parentNode.FindToken(forwardPosition + 1); Contract.ThrowIfTrue(previousToken.RawKind == 0); return previousToken.Span.End; } private static SyntaxNode? GetParentThatContainsGivenSpan(SyntaxNode? node, int position, bool forward) { while (node != null) { var fullSpan = node.FullSpan; if (forward) { if (fullSpan.Start < position) { return node; } } else { if (position > fullSpan.End) { return node; } } node = node.Parent; } return null; } public static bool HasAnyWhitespaceElasticTrivia(SyntaxToken previousToken, SyntaxToken currentToken) { if ((!previousToken.ContainsAnnotations && !currentToken.ContainsAnnotations) || (!previousToken.HasTrailingTrivia && !currentToken.HasLeadingTrivia)) { return false; } return previousToken.TrailingTrivia.HasAnyWhitespaceElasticTrivia() || currentToken.LeadingTrivia.HasAnyWhitespaceElasticTrivia(); } public static bool IsNull<T>(T t) where T : class => t == null; public static bool IsNotNull<T>(T t) where T : class => !IsNull(t); public static TextSpan GetFormattingSpan(SyntaxNode root, TextSpan span) { Contract.ThrowIfNull(root); var startToken = root.FindToken(span.Start).GetPreviousToken(); var endToken = root.FindTokenFromEnd(span.End).GetNextToken(); var startPosition = startToken.SpanStart; var endPosition = endToken.RawKind == 0 ? root.Span.End : endToken.Span.End; return TextSpan.FromBounds(startPosition, endPosition); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Text; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Utilities { internal static class CommonFormattingHelpers { public static readonly Comparison<SuppressOperation> SuppressOperationComparer = (o1, o2) => { return o1.TextSpan.Start - o2.TextSpan.Start; }; public static readonly Comparison<IndentBlockOperation> IndentBlockOperationComparer = (o1, o2) => { // smaller one goes left var s = o1.TextSpan.Start - o2.TextSpan.Start; if (s != 0) { return s; } // bigger one goes left var e = o2.TextSpan.End - o1.TextSpan.End; if (e != 0) { return e; } return 0; }; public static IEnumerable<ValueTuple<SyntaxToken, SyntaxToken>> ConvertToTokenPairs(this SyntaxNode root, IList<TextSpan> spans) { Contract.ThrowIfNull(root); Contract.ThrowIfFalse(spans.Count > 0); if (spans.Count == 1) { // special case, if there is only one span, return right away yield return root.ConvertToTokenPair(spans[0]); yield break; } var previousOne = root.ConvertToTokenPair(spans[0]); // iterate through each spans and make sure each one doesn't overlap each other for (var i = 1; i < spans.Count; i++) { var currentOne = root.ConvertToTokenPair(spans[i]); if (currentOne.Item1.SpanStart <= previousOne.Item2.Span.End) { // oops, looks like two spans are overlapping each other. merge them previousOne = ValueTuple.Create(previousOne.Item1, previousOne.Item2.Span.End < currentOne.Item2.Span.End ? currentOne.Item2 : previousOne.Item2); continue; } // okay, looks like things are in good shape yield return previousOne; // move to next one previousOne = currentOne; } // give out the last one yield return previousOne; } public static ValueTuple<SyntaxToken, SyntaxToken> ConvertToTokenPair(this SyntaxNode root, TextSpan textSpan) { Contract.ThrowIfNull(root); Contract.ThrowIfTrue(textSpan.IsEmpty); var startToken = root.FindToken(textSpan.Start); // empty token, get previous non-zero length token if (startToken.IsMissing) { // if there is no previous token, startToken will be set to SyntaxKind.None startToken = startToken.GetPreviousToken(); } // span is on leading trivia if (textSpan.Start < startToken.SpanStart) { // if there is no previous token, startToken will be set to SyntaxKind.None startToken = startToken.GetPreviousToken(); } // adjust position where we try to search end token var endToken = (root.FullSpan.End <= textSpan.End) ? root.GetLastToken(includeZeroWidth: true) : root.FindToken(textSpan.End); // empty token, get next token if (endToken.IsMissing) { endToken = endToken.GetNextToken(); } // span is on trailing trivia if (endToken.Span.End < textSpan.End) { endToken = endToken.GetNextToken(); } // make sure tokens are not SyntaxKind.None startToken = (startToken.RawKind != 0) ? startToken : root.GetFirstToken(includeZeroWidth: true); endToken = (endToken.RawKind != 0) ? endToken : root.GetLastToken(includeZeroWidth: true); // token is in right order Contract.ThrowIfFalse(startToken.Equals(endToken) || startToken.Span.End <= endToken.SpanStart); return ValueTuple.Create(startToken, endToken); } public static bool IsInvalidTokenRange(this SyntaxNode root, SyntaxToken startToken, SyntaxToken endToken) { // given token must be token exist excluding EndOfFile token. if (startToken.RawKind == 0 || endToken.RawKind == 0) { return true; } if (startToken.Equals(endToken)) { return false; } // regular case. // start token can't be end of file token and start token must be before end token if it's not the same token. return root.FullSpan.End == startToken.SpanStart || startToken.FullSpan.End > endToken.FullSpan.Start; } public static int GetTokenColumn(this SyntaxTree tree, SyntaxToken token, int tabSize) { Contract.ThrowIfNull(tree); Contract.ThrowIfTrue(token.RawKind == 0); var startPosition = token.SpanStart; var line = tree.GetText().Lines.GetLineFromPosition(startPosition); return line.GetColumnFromLineOffset(startPosition - line.Start, tabSize); } public static string GetText(this SourceText text, SyntaxToken token1, SyntaxToken token2) => (token1.RawKind == 0) ? text.ToString(TextSpan.FromBounds(0, token2.SpanStart)) : text.ToString(TextSpan.FromBounds(token1.Span.End, token2.SpanStart)); public static string GetTextBetween(SyntaxToken token1, SyntaxToken token2) { var builder = new StringBuilder(); AppendTextBetween(token1, token2, builder); return builder.ToString(); } public static void AppendTextBetween(SyntaxToken token1, SyntaxToken token2, StringBuilder builder) { Contract.ThrowIfTrue(token1.RawKind == 0 && token2.RawKind == 0); Contract.ThrowIfTrue(token1.Equals(token2)); if (token1.RawKind == 0) { AppendLeadingTriviaText(token2, builder); return; } if (token2.RawKind == 0) { AppendTrailingTriviaText(token1, builder); return; } if (token1.FullSpan.End == token2.FullSpan.Start) { AppendTextBetweenTwoAdjacentTokens(token1, token2, builder); return; } AppendTrailingTriviaText(token1, builder); for (var token = token1.GetNextToken(includeZeroWidth: true); token.FullSpan.End <= token2.FullSpan.Start; token = token.GetNextToken(includeZeroWidth: true)) { builder.Append(token.ToFullString()); } AppendPartialLeadingTriviaText(token2, builder, token1.TrailingTrivia.FullSpan.End); } private static void AppendTextBetweenTwoAdjacentTokens(SyntaxToken token1, SyntaxToken token2, StringBuilder builder) { AppendTrailingTriviaText(token1, builder); AppendLeadingTriviaText(token2, builder); } private static void AppendLeadingTriviaText(SyntaxToken token, StringBuilder builder) { if (!token.HasLeadingTrivia) { return; } foreach (var trivia in token.LeadingTrivia) { builder.Append(trivia.ToFullString()); } } /// <summary> /// If the token1 is expected to be part of the leading trivia of the token2 then the trivia /// before the token1FullSpanEnd, which the fullspan end of the token1 should be ignored /// </summary> private static void AppendPartialLeadingTriviaText(SyntaxToken token, StringBuilder builder, int token1FullSpanEnd) { if (!token.HasLeadingTrivia) { return; } foreach (var trivia in token.LeadingTrivia) { if (trivia.FullSpan.End <= token1FullSpanEnd) { continue; } builder.Append(trivia.ToFullString()); } } private static void AppendTrailingTriviaText(SyntaxToken token, StringBuilder builder) { if (!token.HasTrailingTrivia) { return; } foreach (var trivia in token.TrailingTrivia) { builder.Append(trivia.ToFullString()); } } /// <summary> /// this will create a span that includes its trailing trivia of its previous token and leading trivia of its next token /// for example, for code such as "class A { int ...", if given tokens are "A" and "{", this will return span [] of "class[ A { ]int ..." /// which included trailing trivia of "class" which is previous token of "A", and leading trivia of "int" which is next token of "{" /// </summary> public static TextSpan GetSpanIncludingTrailingAndLeadingTriviaOfAdjacentTokens(SyntaxToken startToken, SyntaxToken endToken) { // most of cases we can just ask previous and next token to create the span, but in some corner cases such as omitted token case, // those navigation function doesn't work, so we have to explore the tree ourselves to create correct span var startPosition = GetStartPositionOfSpan(startToken); var endPosition = GetEndPositionOfSpan(endToken); return TextSpan.FromBounds(startPosition, endPosition); } private static int GetEndPositionOfSpan(SyntaxToken token) { var nextToken = token.GetNextToken(); if (nextToken.RawKind != 0) { return nextToken.SpanStart; } var backwardPosition = token.FullSpan.End; var parentNode = GetParentThatContainsGivenSpan(token.Parent, backwardPosition, forward: false); if (parentNode == null) { // reached the end of tree return token.FullSpan.End; } Contract.ThrowIfFalse(backwardPosition < parentNode.FullSpan.End); nextToken = parentNode.FindToken(backwardPosition + 1); Contract.ThrowIfTrue(nextToken.RawKind == 0); return nextToken.SpanStart; } public static int GetStartPositionOfSpan(SyntaxToken token) { var previousToken = token.GetPreviousToken(); if (previousToken.RawKind != 0) { return previousToken.Span.End; } // first token in the tree var forwardPosition = token.FullSpan.Start; if (forwardPosition <= 0) { return 0; } var parentNode = GetParentThatContainsGivenSpan(token.Parent, forwardPosition, forward: true); Contract.ThrowIfNull(parentNode); Contract.ThrowIfFalse(parentNode.FullSpan.Start < forwardPosition); previousToken = parentNode.FindToken(forwardPosition + 1); Contract.ThrowIfTrue(previousToken.RawKind == 0); return previousToken.Span.End; } private static SyntaxNode? GetParentThatContainsGivenSpan(SyntaxNode? node, int position, bool forward) { while (node != null) { var fullSpan = node.FullSpan; if (forward) { if (fullSpan.Start < position) { return node; } } else { if (position > fullSpan.End) { return node; } } node = node.Parent; } return null; } public static bool HasAnyWhitespaceElasticTrivia(SyntaxToken previousToken, SyntaxToken currentToken) { if ((!previousToken.ContainsAnnotations && !currentToken.ContainsAnnotations) || (!previousToken.HasTrailingTrivia && !currentToken.HasLeadingTrivia)) { return false; } return previousToken.TrailingTrivia.HasAnyWhitespaceElasticTrivia() || currentToken.LeadingTrivia.HasAnyWhitespaceElasticTrivia(); } public static bool IsNull<T>(T t) where T : class => t == null; public static bool IsNotNull<T>(T t) where T : class => !IsNull(t); public static TextSpan GetFormattingSpan(SyntaxNode root, TextSpan span) { Contract.ThrowIfNull(root); var startToken = root.FindToken(span.Start).GetPreviousToken(); var endToken = root.FindTokenFromEnd(span.End).GetNextToken(); var startPosition = startToken.SpanStart; var endPosition = endToken.RawKind == 0 ? root.Span.End : endToken.Span.End; return TextSpan.FromBounds(startPosition, endPosition); } } }
-1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/Compilers/Test/Core/Compilation/SemanticModelExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Text; namespace Microsoft.CodeAnalysis.Test.Utilities { internal static class SemanticModelExtensions { public static void VerifyOperationTree(this SemanticModel model, SyntaxNode node, string expectedOperationTree) { var actualTextBuilder = new StringBuilder(); AppendOperationTree(model, node, actualTextBuilder); OperationTreeVerifier.Verify(expectedOperationTree, actualTextBuilder.ToString()); } public static void AppendOperationTree(this SemanticModel model, SyntaxNode node, StringBuilder actualTextBuilder, int initialIndent = 0) { IOperation operation = model.GetOperation(node); if (operation != null) { string operationTree = OperationTreeVerifier.GetOperationTree(model.Compilation, operation, initialIndent); actualTextBuilder.Append(operationTree); } else { actualTextBuilder.Append($" SemanticModel.GetOperation() returned NULL for node with text: '{node.ToString()}'"); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Text; namespace Microsoft.CodeAnalysis.Test.Utilities { internal static class SemanticModelExtensions { public static void VerifyOperationTree(this SemanticModel model, SyntaxNode node, string expectedOperationTree) { var actualTextBuilder = new StringBuilder(); AppendOperationTree(model, node, actualTextBuilder); OperationTreeVerifier.Verify(expectedOperationTree, actualTextBuilder.ToString()); } public static void AppendOperationTree(this SemanticModel model, SyntaxNode node, StringBuilder actualTextBuilder, int initialIndent = 0) { IOperation operation = model.GetOperation(node); if (operation != null) { string operationTree = OperationTreeVerifier.GetOperationTree(model.Compilation, operation, initialIndent); actualTextBuilder.Append(operationTree); } else { actualTextBuilder.Append($" SemanticModel.GetOperation() returned NULL for node with text: '{node.ToString()}'"); } } } }
-1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/Workspaces/Core/Portable/CodeGeneration/CodeGenerationSymbolFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CodeGeneration { /// <summary> /// Generates symbols that describe declarations to be generated. /// </summary> internal static class CodeGenerationSymbolFactory { /// <summary> /// Determines if the symbol is purely a code generation symbol. /// </summary> public static bool IsCodeGenerationSymbol(this ISymbol symbol) => symbol is CodeGenerationSymbol; /// <summary> /// Creates an event symbol that can be used to describe an event declaration. /// </summary> public static IEventSymbol CreateEventSymbol( ImmutableArray<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers, ITypeSymbol type, ImmutableArray<IEventSymbol> explicitInterfaceImplementations, string name, IMethodSymbol? addMethod = null, IMethodSymbol? removeMethod = null, IMethodSymbol? raiseMethod = null) { var result = new CodeGenerationEventSymbol(null, attributes, accessibility, modifiers, type, explicitInterfaceImplementations, name, addMethod, removeMethod, raiseMethod); CodeGenerationEventInfo.Attach(result, modifiers.IsUnsafe); return result; } internal static IPropertySymbol CreatePropertySymbol( INamedTypeSymbol? containingType, ImmutableArray<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers, ITypeSymbol type, RefKind refKind, ImmutableArray<IPropertySymbol> explicitInterfaceImplementations, string name, ImmutableArray<IParameterSymbol> parameters, IMethodSymbol? getMethod, IMethodSymbol? setMethod, bool isIndexer = false, SyntaxNode? initializer = null) { var result = new CodeGenerationPropertySymbol( containingType, attributes, accessibility, modifiers, type, refKind, explicitInterfaceImplementations, name, isIndexer, parameters, getMethod, setMethod); CodeGenerationPropertyInfo.Attach(result, modifiers.IsNew, modifiers.IsUnsafe, initializer); return result; } /// <summary> /// Creates a property symbol that can be used to describe a property declaration. /// </summary> public static IPropertySymbol CreatePropertySymbol( ImmutableArray<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers, ITypeSymbol type, RefKind refKind, ImmutableArray<IPropertySymbol> explicitInterfaceImplementations, string name, ImmutableArray<IParameterSymbol> parameters, IMethodSymbol? getMethod, IMethodSymbol? setMethod, bool isIndexer = false) { return CreatePropertySymbol( containingType: null, attributes: attributes, accessibility: accessibility, modifiers: modifiers, type: type, refKind: refKind, explicitInterfaceImplementations: explicitInterfaceImplementations, name: name, parameters: parameters, getMethod: getMethod, setMethod: setMethod, isIndexer: isIndexer); } /// <summary> /// Creates a field symbol that can be used to describe a field declaration. /// </summary> public static IFieldSymbol CreateFieldSymbol( ImmutableArray<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers, ITypeSymbol type, string name, bool hasConstantValue = false, object? constantValue = null, SyntaxNode? initializer = null) { var result = new CodeGenerationFieldSymbol(null, attributes, accessibility, modifiers, type, name, hasConstantValue, constantValue); CodeGenerationFieldInfo.Attach(result, modifiers.IsUnsafe, modifiers.IsWithEvents, initializer); return result; } /// <summary> /// Creates a constructor symbol that can be used to describe a constructor declaration. /// </summary> public static IMethodSymbol CreateConstructorSymbol( ImmutableArray<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers, string typeName, ImmutableArray<IParameterSymbol> parameters, ImmutableArray<SyntaxNode> statements = default, ImmutableArray<SyntaxNode> baseConstructorArguments = default, ImmutableArray<SyntaxNode> thisConstructorArguments = default, bool isPrimaryConstructor = false) { var result = new CodeGenerationConstructorSymbol(null, attributes, accessibility, modifiers, parameters); CodeGenerationConstructorInfo.Attach(result, isPrimaryConstructor, modifiers.IsUnsafe, typeName, statements, baseConstructorArguments, thisConstructorArguments); return result; } /// <summary> /// Creates a destructor symbol that can be used to describe a destructor declaration. /// </summary> public static IMethodSymbol CreateDestructorSymbol( ImmutableArray<AttributeData> attributes, string typeName, ImmutableArray<SyntaxNode> statements = default) { var result = new CodeGenerationDestructorSymbol(null, attributes); CodeGenerationDestructorInfo.Attach(result, typeName, statements); return result; } internal static IMethodSymbol CreateMethodSymbol( INamedTypeSymbol? containingType, ImmutableArray<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers, ITypeSymbol? returnType, RefKind refKind, ImmutableArray<IMethodSymbol> explicitInterfaceImplementations, string name, ImmutableArray<ITypeParameterSymbol> typeParameters, ImmutableArray<IParameterSymbol> parameters, ImmutableArray<SyntaxNode> statements = default, ImmutableArray<SyntaxNode> handlesExpressions = default, ImmutableArray<AttributeData> returnTypeAttributes = default, MethodKind methodKind = MethodKind.Ordinary, bool isInitOnly = false) { var result = new CodeGenerationMethodSymbol(containingType, attributes, accessibility, modifiers, returnType, refKind, explicitInterfaceImplementations, name, typeParameters, parameters, returnTypeAttributes, documentationCommentXml: null, methodKind, isInitOnly); CodeGenerationMethodInfo.Attach(result, modifiers.IsNew, modifiers.IsUnsafe, modifiers.IsPartial, modifiers.IsAsync, statements, handlesExpressions); return result; } /// <summary> /// Creates a method symbol that can be used to describe a method declaration. /// </summary> public static IMethodSymbol CreateMethodSymbol( ImmutableArray<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers, ITypeSymbol? returnType, RefKind refKind, ImmutableArray<IMethodSymbol> explicitInterfaceImplementations, string name, ImmutableArray<ITypeParameterSymbol> typeParameters, ImmutableArray<IParameterSymbol> parameters, ImmutableArray<SyntaxNode> statements = default, ImmutableArray<SyntaxNode> handlesExpressions = default, ImmutableArray<AttributeData> returnTypeAttributes = default, MethodKind methodKind = MethodKind.Ordinary, bool isInitOnly = false) { return CreateMethodSymbol(null, attributes, accessibility, modifiers, returnType, refKind, explicitInterfaceImplementations, name, typeParameters, parameters, statements, handlesExpressions, returnTypeAttributes, methodKind, isInitOnly); } /// <summary> /// Creates a method symbol that can be used to describe an operator declaration. /// </summary> public static IMethodSymbol CreateOperatorSymbol( ImmutableArray<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers, ITypeSymbol returnType, CodeGenerationOperatorKind operatorKind, ImmutableArray<IParameterSymbol> parameters, ImmutableArray<SyntaxNode> statements = default, ImmutableArray<AttributeData> returnTypeAttributes = default, string? documentationCommentXml = null) { var expectedParameterCount = CodeGenerationOperatorSymbol.GetParameterCount(operatorKind); if (parameters.Length != expectedParameterCount) { var message = expectedParameterCount == 1 ? WorkspacesResources.Invalid_number_of_parameters_for_unary_operator : WorkspacesResources.Invalid_number_of_parameters_for_binary_operator; throw new ArgumentException(message, nameof(parameters)); } var result = new CodeGenerationOperatorSymbol(null, attributes, accessibility, modifiers, returnType, operatorKind, parameters, returnTypeAttributes, documentationCommentXml); CodeGenerationMethodInfo.Attach(result, modifiers.IsNew, modifiers.IsUnsafe, modifiers.IsPartial, modifiers.IsAsync, statements, handlesExpressions: default); return result; } /// <summary> /// Creates a method symbol that can be used to describe a conversion declaration. /// </summary> public static IMethodSymbol CreateConversionSymbol( ITypeSymbol toType, IParameterSymbol fromType, INamedTypeSymbol? containingType = null, bool isImplicit = false, ImmutableArray<SyntaxNode> statements = default, ImmutableArray<AttributeData> toTypeAttributes = default, string? documentationCommentXml = null) { return CreateConversionSymbol( attributes: default, accessibility: Accessibility.Public, DeclarationModifiers.Static, toType, fromType, containingType, isImplicit, statements, toTypeAttributes, documentationCommentXml); } /// <summary> /// Creates a method symbol that can be used to describe a conversion declaration. /// </summary> public static IMethodSymbol CreateConversionSymbol( ImmutableArray<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers, ITypeSymbol toType, IParameterSymbol fromType, INamedTypeSymbol? containingType = null, bool isImplicit = false, ImmutableArray<SyntaxNode> statements = default, ImmutableArray<AttributeData> toTypeAttributes = default, string? documentationCommentXml = null) { var result = new CodeGenerationConversionSymbol(containingType, attributes, accessibility, modifiers, toType, fromType, isImplicit, toTypeAttributes, documentationCommentXml); CodeGenerationMethodInfo.Attach(result, modifiers.IsNew, modifiers.IsUnsafe, modifiers.IsPartial, modifiers.IsAsync, statements, handlesExpressions: default); return result; } /// <summary> /// Creates a parameter symbol that can be used to describe a parameter declaration. /// </summary> public static IParameterSymbol CreateParameterSymbol(ITypeSymbol type, string name) => CreateParameterSymbol(RefKind.None, type, name); public static IParameterSymbol CreateParameterSymbol(RefKind refKind, ITypeSymbol type, string name) { return CreateParameterSymbol( attributes: default, refKind, isParams: false, type: type, name: name, isOptional: false); } /// <summary> /// Creates a parameter symbol that can be used to describe a parameter declaration. /// </summary> public static IParameterSymbol CreateParameterSymbol( ImmutableArray<AttributeData> attributes, RefKind refKind, bool isParams, ITypeSymbol type, string name, bool isOptional = false, bool hasDefaultValue = false, object? defaultValue = null) { return new CodeGenerationParameterSymbol(null, attributes, refKind, isParams, type, name, isOptional, hasDefaultValue, defaultValue); } /// <summary> /// Creates a parameter symbol that can be used to describe a parameter declaration. /// </summary> internal static IParameterSymbol CreateParameterSymbol( IParameterSymbol parameter, ImmutableArray<AttributeData>? attributes = null, RefKind? refKind = null, bool? isParams = null, ITypeSymbol? type = null, Optional<string> name = default, bool? isOptional = null, bool? hasDefaultValue = null, Optional<object> defaultValue = default) { return new CodeGenerationParameterSymbol( containingType: null, attributes ?? parameter.GetAttributes(), refKind ?? parameter.RefKind, isParams ?? parameter.IsParams, type ?? parameter.Type, name.HasValue ? name.Value : parameter.Name, isOptional ?? parameter.IsOptional, hasDefaultValue ?? parameter.HasExplicitDefaultValue, defaultValue.HasValue ? defaultValue.Value : parameter.HasExplicitDefaultValue ? parameter.ExplicitDefaultValue : null); } /// <summary> /// Creates a parameter symbol that can be used to describe a parameter declaration. /// </summary> public static ITypeParameterSymbol CreateTypeParameterSymbol(string name, int ordinal = 0) { return CreateTypeParameter( attributes: default, varianceKind: VarianceKind.None, name: name, constraintTypes: ImmutableArray.Create<ITypeSymbol>(), hasConstructorConstraint: false, hasReferenceConstraint: false, hasValueConstraint: false, hasUnmanagedConstraint: false, hasNotNullConstraint: false, ordinal: ordinal); } /// <summary> /// Creates a type parameter symbol that can be used to describe a type parameter declaration. /// </summary> public static ITypeParameterSymbol CreateTypeParameter( ImmutableArray<AttributeData> attributes, VarianceKind varianceKind, string name, ImmutableArray<ITypeSymbol> constraintTypes, NullableAnnotation nullableAnnotation = NullableAnnotation.None, bool hasConstructorConstraint = false, bool hasReferenceConstraint = false, bool hasUnmanagedConstraint = false, bool hasValueConstraint = false, bool hasNotNullConstraint = false, int ordinal = 0) { return new CodeGenerationTypeParameterSymbol(null, attributes, varianceKind, name, nullableAnnotation, constraintTypes, hasConstructorConstraint, hasReferenceConstraint, hasValueConstraint, hasUnmanagedConstraint, hasNotNullConstraint, ordinal); } /// <summary> /// Creates a pointer type symbol that can be used to describe a pointer type reference. /// </summary> public static IPointerTypeSymbol CreatePointerTypeSymbol(ITypeSymbol pointedAtType) => new CodeGenerationPointerTypeSymbol(pointedAtType); /// <summary> /// Creates an array type symbol that can be used to describe an array type reference. /// </summary> public static IArrayTypeSymbol CreateArrayTypeSymbol(ITypeSymbol elementType, int rank = 1, NullableAnnotation nullableAnnotation = NullableAnnotation.None) => new CodeGenerationArrayTypeSymbol(elementType, rank, nullableAnnotation); internal static IMethodSymbol CreateAccessorSymbol( IMethodSymbol accessor, ImmutableArray<AttributeData> attributes = default, Accessibility? accessibility = null, ImmutableArray<IMethodSymbol> explicitInterfaceImplementations = default, ImmutableArray<SyntaxNode> statements = default) { return CreateMethodSymbol( attributes, accessibility ?? accessor.DeclaredAccessibility, accessor.GetSymbolModifiers().WithIsAbstract(statements == null), accessor.ReturnType, accessor.RefKind, explicitInterfaceImplementations.IsDefault ? accessor.ExplicitInterfaceImplementations : explicitInterfaceImplementations, accessor.Name, accessor.TypeParameters, accessor.Parameters, statements: statements, returnTypeAttributes: accessor.GetReturnTypeAttributes(), methodKind: accessor.MethodKind, isInitOnly: accessor.IsInitOnly); } /// <summary> /// Creates an method type symbol that can be used to describe an accessor method declaration. /// </summary> public static IMethodSymbol CreateAccessorSymbol( ImmutableArray<AttributeData> attributes, Accessibility accessibility, ImmutableArray<SyntaxNode> statements) { return CreateMethodSymbol( attributes, accessibility, new DeclarationModifiers(isAbstract: statements == null), returnType: null, refKind: RefKind.None, explicitInterfaceImplementations: default, name: string.Empty, typeParameters: default, parameters: default, statements: statements); } /// <summary> /// Create attribute data that can be used in describing an attribute declaration. /// </summary> public static AttributeData CreateAttributeData( INamedTypeSymbol attributeClass, ImmutableArray<TypedConstant> constructorArguments = default, ImmutableArray<KeyValuePair<string, TypedConstant>> namedArguments = default) { return new CodeGenerationAttributeData(attributeClass, constructorArguments, namedArguments); } /// <summary> /// Creates a named type symbol that can be used to describe a named type declaration. /// </summary> public static INamedTypeSymbol CreateNamedTypeSymbol( ImmutableArray<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers, TypeKind typeKind, string name, ImmutableArray<ITypeParameterSymbol> typeParameters = default, INamedTypeSymbol? baseType = null, ImmutableArray<INamedTypeSymbol> interfaces = default, SpecialType specialType = SpecialType.None, ImmutableArray<ISymbol> members = default, NullableAnnotation nullableAnnotation = NullableAnnotation.None, IAssemblySymbol? containingAssembly = null) { return CreateNamedTypeSymbol(attributes, accessibility, modifiers, isRecord: false, typeKind, name, typeParameters, baseType, interfaces, specialType, members, nullableAnnotation, containingAssembly); } /// <summary> /// Creates a named type symbol that can be used to describe a named type declaration. /// </summary> public static INamedTypeSymbol CreateNamedTypeSymbol( ImmutableArray<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers, bool isRecord, TypeKind typeKind, string name, ImmutableArray<ITypeParameterSymbol> typeParameters = default, INamedTypeSymbol? baseType = null, ImmutableArray<INamedTypeSymbol> interfaces = default, SpecialType specialType = SpecialType.None, ImmutableArray<ISymbol> members = default, NullableAnnotation nullableAnnotation = NullableAnnotation.None, IAssemblySymbol? containingAssembly = null) { members = members.NullToEmpty(); return new CodeGenerationNamedTypeSymbol( containingAssembly, null, attributes, accessibility, modifiers, isRecord, typeKind, name, typeParameters, baseType, interfaces, specialType, nullableAnnotation, members.WhereAsArray(m => !(m is INamedTypeSymbol)), members.OfType<INamedTypeSymbol>().Select(n => n.ToCodeGenerationSymbol()).ToImmutableArray(), enumUnderlyingType: null); } /// <summary> /// Creates a method type symbol that can be used to describe a delegate type declaration. /// </summary> public static CodeGenerationNamedTypeSymbol CreateDelegateTypeSymbol( ImmutableArray<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers, ITypeSymbol returnType, RefKind refKind, string name, ImmutableArray<ITypeParameterSymbol> typeParameters = default, ImmutableArray<IParameterSymbol> parameters = default, NullableAnnotation nullableAnnotation = NullableAnnotation.None) { var invokeMethod = CreateMethodSymbol( attributes: default, accessibility: Accessibility.Public, modifiers: new DeclarationModifiers(), returnType: returnType, refKind: refKind, explicitInterfaceImplementations: default, name: "Invoke", typeParameters: default, parameters: parameters); return new CodeGenerationNamedTypeSymbol( containingAssembly: null, containingType: null, attributes: attributes, declaredAccessibility: accessibility, modifiers: modifiers, isRecord: false, typeKind: TypeKind.Delegate, name: name, typeParameters: typeParameters, baseType: null, interfaces: default, specialType: SpecialType.None, members: ImmutableArray.Create<ISymbol>(invokeMethod), typeMembers: ImmutableArray<CodeGenerationAbstractNamedTypeSymbol>.Empty, nullableAnnotation: nullableAnnotation, enumUnderlyingType: null); } /// <summary> /// Creates a namespace symbol that can be used to describe a namespace declaration. /// </summary> public static INamespaceSymbol CreateNamespaceSymbol(string name, IList<ISymbol>? imports = null, IList<INamespaceOrTypeSymbol>? members = null) { var @namespace = new CodeGenerationNamespaceSymbol(name, members); CodeGenerationNamespaceInfo.Attach(@namespace, imports); return @namespace; } internal static IMethodSymbol CreateMethodSymbol( IMethodSymbol method, ImmutableArray<AttributeData> attributes = default, Accessibility? accessibility = null, DeclarationModifiers? modifiers = null, ImmutableArray<IMethodSymbol> explicitInterfaceImplementations = default, string? name = null, ImmutableArray<IParameterSymbol>? parameters = null, ImmutableArray<SyntaxNode> statements = default, INamedTypeSymbol? containingType = null, ITypeSymbol? returnType = null, Optional<ImmutableArray<AttributeData>> returnTypeAttributes = default) { return CreateMethodSymbol( containingType, attributes, accessibility ?? method.DeclaredAccessibility, modifiers ?? method.GetSymbolModifiers(), returnType ?? method.ReturnType, method.RefKind, explicitInterfaceImplementations, name ?? method.Name, method.TypeParameters, parameters ?? method.Parameters, statements, returnTypeAttributes: returnTypeAttributes.HasValue ? returnTypeAttributes.Value : method.GetReturnTypeAttributes(), methodKind: method.MethodKind, isInitOnly: method.IsInitOnly); } internal static IPropertySymbol CreatePropertySymbol( IPropertySymbol property, ImmutableArray<AttributeData> attributes = default, ImmutableArray<IParameterSymbol>? parameters = null, Accessibility? accessibility = null, DeclarationModifiers? modifiers = null, ImmutableArray<IPropertySymbol> explicitInterfaceImplementations = default, string? name = null, bool? isIndexer = null, IMethodSymbol? getMethod = null, IMethodSymbol? setMethod = null) { return CreatePropertySymbol( attributes, accessibility ?? property.DeclaredAccessibility, modifiers ?? property.GetSymbolModifiers(), property.Type, property.RefKind, explicitInterfaceImplementations, name ?? property.Name, parameters ?? property.Parameters, getMethod, setMethod, isIndexer ?? property.IsIndexer); } internal static IEventSymbol CreateEventSymbol( IEventSymbol @event, ImmutableArray<AttributeData> attributes = default, Accessibility? accessibility = null, DeclarationModifiers? modifiers = null, ImmutableArray<IEventSymbol> explicitInterfaceImplementations = default, string? name = null, IMethodSymbol? addMethod = null, IMethodSymbol? removeMethod = null) { return CreateEventSymbol( attributes, accessibility ?? @event.DeclaredAccessibility, modifiers ?? @event.GetSymbolModifiers(), @event.Type, explicitInterfaceImplementations, name ?? @event.Name, addMethod, removeMethod); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CodeGeneration { /// <summary> /// Generates symbols that describe declarations to be generated. /// </summary> internal static class CodeGenerationSymbolFactory { /// <summary> /// Determines if the symbol is purely a code generation symbol. /// </summary> public static bool IsCodeGenerationSymbol(this ISymbol symbol) => symbol is CodeGenerationSymbol; /// <summary> /// Creates an event symbol that can be used to describe an event declaration. /// </summary> public static IEventSymbol CreateEventSymbol( ImmutableArray<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers, ITypeSymbol type, ImmutableArray<IEventSymbol> explicitInterfaceImplementations, string name, IMethodSymbol? addMethod = null, IMethodSymbol? removeMethod = null, IMethodSymbol? raiseMethod = null) { var result = new CodeGenerationEventSymbol(null, attributes, accessibility, modifiers, type, explicitInterfaceImplementations, name, addMethod, removeMethod, raiseMethod); CodeGenerationEventInfo.Attach(result, modifiers.IsUnsafe); return result; } internal static IPropertySymbol CreatePropertySymbol( INamedTypeSymbol? containingType, ImmutableArray<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers, ITypeSymbol type, RefKind refKind, ImmutableArray<IPropertySymbol> explicitInterfaceImplementations, string name, ImmutableArray<IParameterSymbol> parameters, IMethodSymbol? getMethod, IMethodSymbol? setMethod, bool isIndexer = false, SyntaxNode? initializer = null) { var result = new CodeGenerationPropertySymbol( containingType, attributes, accessibility, modifiers, type, refKind, explicitInterfaceImplementations, name, isIndexer, parameters, getMethod, setMethod); CodeGenerationPropertyInfo.Attach(result, modifiers.IsNew, modifiers.IsUnsafe, initializer); return result; } /// <summary> /// Creates a property symbol that can be used to describe a property declaration. /// </summary> public static IPropertySymbol CreatePropertySymbol( ImmutableArray<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers, ITypeSymbol type, RefKind refKind, ImmutableArray<IPropertySymbol> explicitInterfaceImplementations, string name, ImmutableArray<IParameterSymbol> parameters, IMethodSymbol? getMethod, IMethodSymbol? setMethod, bool isIndexer = false) { return CreatePropertySymbol( containingType: null, attributes: attributes, accessibility: accessibility, modifiers: modifiers, type: type, refKind: refKind, explicitInterfaceImplementations: explicitInterfaceImplementations, name: name, parameters: parameters, getMethod: getMethod, setMethod: setMethod, isIndexer: isIndexer); } /// <summary> /// Creates a field symbol that can be used to describe a field declaration. /// </summary> public static IFieldSymbol CreateFieldSymbol( ImmutableArray<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers, ITypeSymbol type, string name, bool hasConstantValue = false, object? constantValue = null, SyntaxNode? initializer = null) { var result = new CodeGenerationFieldSymbol(null, attributes, accessibility, modifiers, type, name, hasConstantValue, constantValue); CodeGenerationFieldInfo.Attach(result, modifiers.IsUnsafe, modifiers.IsWithEvents, initializer); return result; } /// <summary> /// Creates a constructor symbol that can be used to describe a constructor declaration. /// </summary> public static IMethodSymbol CreateConstructorSymbol( ImmutableArray<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers, string typeName, ImmutableArray<IParameterSymbol> parameters, ImmutableArray<SyntaxNode> statements = default, ImmutableArray<SyntaxNode> baseConstructorArguments = default, ImmutableArray<SyntaxNode> thisConstructorArguments = default, bool isPrimaryConstructor = false) { var result = new CodeGenerationConstructorSymbol(null, attributes, accessibility, modifiers, parameters); CodeGenerationConstructorInfo.Attach(result, isPrimaryConstructor, modifiers.IsUnsafe, typeName, statements, baseConstructorArguments, thisConstructorArguments); return result; } /// <summary> /// Creates a destructor symbol that can be used to describe a destructor declaration. /// </summary> public static IMethodSymbol CreateDestructorSymbol( ImmutableArray<AttributeData> attributes, string typeName, ImmutableArray<SyntaxNode> statements = default) { var result = new CodeGenerationDestructorSymbol(null, attributes); CodeGenerationDestructorInfo.Attach(result, typeName, statements); return result; } internal static IMethodSymbol CreateMethodSymbol( INamedTypeSymbol? containingType, ImmutableArray<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers, ITypeSymbol? returnType, RefKind refKind, ImmutableArray<IMethodSymbol> explicitInterfaceImplementations, string name, ImmutableArray<ITypeParameterSymbol> typeParameters, ImmutableArray<IParameterSymbol> parameters, ImmutableArray<SyntaxNode> statements = default, ImmutableArray<SyntaxNode> handlesExpressions = default, ImmutableArray<AttributeData> returnTypeAttributes = default, MethodKind methodKind = MethodKind.Ordinary, bool isInitOnly = false) { var result = new CodeGenerationMethodSymbol(containingType, attributes, accessibility, modifiers, returnType, refKind, explicitInterfaceImplementations, name, typeParameters, parameters, returnTypeAttributes, documentationCommentXml: null, methodKind, isInitOnly); CodeGenerationMethodInfo.Attach(result, modifiers.IsNew, modifiers.IsUnsafe, modifiers.IsPartial, modifiers.IsAsync, statements, handlesExpressions); return result; } /// <summary> /// Creates a method symbol that can be used to describe a method declaration. /// </summary> public static IMethodSymbol CreateMethodSymbol( ImmutableArray<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers, ITypeSymbol? returnType, RefKind refKind, ImmutableArray<IMethodSymbol> explicitInterfaceImplementations, string name, ImmutableArray<ITypeParameterSymbol> typeParameters, ImmutableArray<IParameterSymbol> parameters, ImmutableArray<SyntaxNode> statements = default, ImmutableArray<SyntaxNode> handlesExpressions = default, ImmutableArray<AttributeData> returnTypeAttributes = default, MethodKind methodKind = MethodKind.Ordinary, bool isInitOnly = false) { return CreateMethodSymbol(null, attributes, accessibility, modifiers, returnType, refKind, explicitInterfaceImplementations, name, typeParameters, parameters, statements, handlesExpressions, returnTypeAttributes, methodKind, isInitOnly); } /// <summary> /// Creates a method symbol that can be used to describe an operator declaration. /// </summary> public static IMethodSymbol CreateOperatorSymbol( ImmutableArray<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers, ITypeSymbol returnType, CodeGenerationOperatorKind operatorKind, ImmutableArray<IParameterSymbol> parameters, ImmutableArray<SyntaxNode> statements = default, ImmutableArray<AttributeData> returnTypeAttributes = default, string? documentationCommentXml = null) { var expectedParameterCount = CodeGenerationOperatorSymbol.GetParameterCount(operatorKind); if (parameters.Length != expectedParameterCount) { var message = expectedParameterCount == 1 ? WorkspacesResources.Invalid_number_of_parameters_for_unary_operator : WorkspacesResources.Invalid_number_of_parameters_for_binary_operator; throw new ArgumentException(message, nameof(parameters)); } var result = new CodeGenerationOperatorSymbol(null, attributes, accessibility, modifiers, returnType, operatorKind, parameters, returnTypeAttributes, documentationCommentXml); CodeGenerationMethodInfo.Attach(result, modifiers.IsNew, modifiers.IsUnsafe, modifiers.IsPartial, modifiers.IsAsync, statements, handlesExpressions: default); return result; } /// <summary> /// Creates a method symbol that can be used to describe a conversion declaration. /// </summary> public static IMethodSymbol CreateConversionSymbol( ITypeSymbol toType, IParameterSymbol fromType, INamedTypeSymbol? containingType = null, bool isImplicit = false, ImmutableArray<SyntaxNode> statements = default, ImmutableArray<AttributeData> toTypeAttributes = default, string? documentationCommentXml = null) { return CreateConversionSymbol( attributes: default, accessibility: Accessibility.Public, DeclarationModifiers.Static, toType, fromType, containingType, isImplicit, statements, toTypeAttributes, documentationCommentXml); } /// <summary> /// Creates a method symbol that can be used to describe a conversion declaration. /// </summary> public static IMethodSymbol CreateConversionSymbol( ImmutableArray<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers, ITypeSymbol toType, IParameterSymbol fromType, INamedTypeSymbol? containingType = null, bool isImplicit = false, ImmutableArray<SyntaxNode> statements = default, ImmutableArray<AttributeData> toTypeAttributes = default, string? documentationCommentXml = null) { var result = new CodeGenerationConversionSymbol(containingType, attributes, accessibility, modifiers, toType, fromType, isImplicit, toTypeAttributes, documentationCommentXml); CodeGenerationMethodInfo.Attach(result, modifiers.IsNew, modifiers.IsUnsafe, modifiers.IsPartial, modifiers.IsAsync, statements, handlesExpressions: default); return result; } /// <summary> /// Creates a parameter symbol that can be used to describe a parameter declaration. /// </summary> public static IParameterSymbol CreateParameterSymbol(ITypeSymbol type, string name) => CreateParameterSymbol(RefKind.None, type, name); public static IParameterSymbol CreateParameterSymbol(RefKind refKind, ITypeSymbol type, string name) { return CreateParameterSymbol( attributes: default, refKind, isParams: false, type: type, name: name, isOptional: false); } /// <summary> /// Creates a parameter symbol that can be used to describe a parameter declaration. /// </summary> public static IParameterSymbol CreateParameterSymbol( ImmutableArray<AttributeData> attributes, RefKind refKind, bool isParams, ITypeSymbol type, string name, bool isOptional = false, bool hasDefaultValue = false, object? defaultValue = null) { return new CodeGenerationParameterSymbol(null, attributes, refKind, isParams, type, name, isOptional, hasDefaultValue, defaultValue); } /// <summary> /// Creates a parameter symbol that can be used to describe a parameter declaration. /// </summary> internal static IParameterSymbol CreateParameterSymbol( IParameterSymbol parameter, ImmutableArray<AttributeData>? attributes = null, RefKind? refKind = null, bool? isParams = null, ITypeSymbol? type = null, Optional<string> name = default, bool? isOptional = null, bool? hasDefaultValue = null, Optional<object> defaultValue = default) { return new CodeGenerationParameterSymbol( containingType: null, attributes ?? parameter.GetAttributes(), refKind ?? parameter.RefKind, isParams ?? parameter.IsParams, type ?? parameter.Type, name.HasValue ? name.Value : parameter.Name, isOptional ?? parameter.IsOptional, hasDefaultValue ?? parameter.HasExplicitDefaultValue, defaultValue.HasValue ? defaultValue.Value : parameter.HasExplicitDefaultValue ? parameter.ExplicitDefaultValue : null); } /// <summary> /// Creates a parameter symbol that can be used to describe a parameter declaration. /// </summary> public static ITypeParameterSymbol CreateTypeParameterSymbol(string name, int ordinal = 0) { return CreateTypeParameter( attributes: default, varianceKind: VarianceKind.None, name: name, constraintTypes: ImmutableArray.Create<ITypeSymbol>(), hasConstructorConstraint: false, hasReferenceConstraint: false, hasValueConstraint: false, hasUnmanagedConstraint: false, hasNotNullConstraint: false, ordinal: ordinal); } /// <summary> /// Creates a type parameter symbol that can be used to describe a type parameter declaration. /// </summary> public static ITypeParameterSymbol CreateTypeParameter( ImmutableArray<AttributeData> attributes, VarianceKind varianceKind, string name, ImmutableArray<ITypeSymbol> constraintTypes, NullableAnnotation nullableAnnotation = NullableAnnotation.None, bool hasConstructorConstraint = false, bool hasReferenceConstraint = false, bool hasUnmanagedConstraint = false, bool hasValueConstraint = false, bool hasNotNullConstraint = false, int ordinal = 0) { return new CodeGenerationTypeParameterSymbol(null, attributes, varianceKind, name, nullableAnnotation, constraintTypes, hasConstructorConstraint, hasReferenceConstraint, hasValueConstraint, hasUnmanagedConstraint, hasNotNullConstraint, ordinal); } /// <summary> /// Creates a pointer type symbol that can be used to describe a pointer type reference. /// </summary> public static IPointerTypeSymbol CreatePointerTypeSymbol(ITypeSymbol pointedAtType) => new CodeGenerationPointerTypeSymbol(pointedAtType); /// <summary> /// Creates an array type symbol that can be used to describe an array type reference. /// </summary> public static IArrayTypeSymbol CreateArrayTypeSymbol(ITypeSymbol elementType, int rank = 1, NullableAnnotation nullableAnnotation = NullableAnnotation.None) => new CodeGenerationArrayTypeSymbol(elementType, rank, nullableAnnotation); internal static IMethodSymbol CreateAccessorSymbol( IMethodSymbol accessor, ImmutableArray<AttributeData> attributes = default, Accessibility? accessibility = null, ImmutableArray<IMethodSymbol> explicitInterfaceImplementations = default, ImmutableArray<SyntaxNode> statements = default) { return CreateMethodSymbol( attributes, accessibility ?? accessor.DeclaredAccessibility, accessor.GetSymbolModifiers().WithIsAbstract(statements == null), accessor.ReturnType, accessor.RefKind, explicitInterfaceImplementations.IsDefault ? accessor.ExplicitInterfaceImplementations : explicitInterfaceImplementations, accessor.Name, accessor.TypeParameters, accessor.Parameters, statements: statements, returnTypeAttributes: accessor.GetReturnTypeAttributes(), methodKind: accessor.MethodKind, isInitOnly: accessor.IsInitOnly); } /// <summary> /// Creates an method type symbol that can be used to describe an accessor method declaration. /// </summary> public static IMethodSymbol CreateAccessorSymbol( ImmutableArray<AttributeData> attributes, Accessibility accessibility, ImmutableArray<SyntaxNode> statements) { return CreateMethodSymbol( attributes, accessibility, new DeclarationModifiers(isAbstract: statements == null), returnType: null, refKind: RefKind.None, explicitInterfaceImplementations: default, name: string.Empty, typeParameters: default, parameters: default, statements: statements); } /// <summary> /// Create attribute data that can be used in describing an attribute declaration. /// </summary> public static AttributeData CreateAttributeData( INamedTypeSymbol attributeClass, ImmutableArray<TypedConstant> constructorArguments = default, ImmutableArray<KeyValuePair<string, TypedConstant>> namedArguments = default) { return new CodeGenerationAttributeData(attributeClass, constructorArguments, namedArguments); } /// <summary> /// Creates a named type symbol that can be used to describe a named type declaration. /// </summary> public static INamedTypeSymbol CreateNamedTypeSymbol( ImmutableArray<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers, TypeKind typeKind, string name, ImmutableArray<ITypeParameterSymbol> typeParameters = default, INamedTypeSymbol? baseType = null, ImmutableArray<INamedTypeSymbol> interfaces = default, SpecialType specialType = SpecialType.None, ImmutableArray<ISymbol> members = default, NullableAnnotation nullableAnnotation = NullableAnnotation.None, IAssemblySymbol? containingAssembly = null) { return CreateNamedTypeSymbol(attributes, accessibility, modifiers, isRecord: false, typeKind, name, typeParameters, baseType, interfaces, specialType, members, nullableAnnotation, containingAssembly); } /// <summary> /// Creates a named type symbol that can be used to describe a named type declaration. /// </summary> public static INamedTypeSymbol CreateNamedTypeSymbol( ImmutableArray<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers, bool isRecord, TypeKind typeKind, string name, ImmutableArray<ITypeParameterSymbol> typeParameters = default, INamedTypeSymbol? baseType = null, ImmutableArray<INamedTypeSymbol> interfaces = default, SpecialType specialType = SpecialType.None, ImmutableArray<ISymbol> members = default, NullableAnnotation nullableAnnotation = NullableAnnotation.None, IAssemblySymbol? containingAssembly = null) { members = members.NullToEmpty(); return new CodeGenerationNamedTypeSymbol( containingAssembly, null, attributes, accessibility, modifiers, isRecord, typeKind, name, typeParameters, baseType, interfaces, specialType, nullableAnnotation, members.WhereAsArray(m => !(m is INamedTypeSymbol)), members.OfType<INamedTypeSymbol>().Select(n => n.ToCodeGenerationSymbol()).ToImmutableArray(), enumUnderlyingType: null); } /// <summary> /// Creates a method type symbol that can be used to describe a delegate type declaration. /// </summary> public static CodeGenerationNamedTypeSymbol CreateDelegateTypeSymbol( ImmutableArray<AttributeData> attributes, Accessibility accessibility, DeclarationModifiers modifiers, ITypeSymbol returnType, RefKind refKind, string name, ImmutableArray<ITypeParameterSymbol> typeParameters = default, ImmutableArray<IParameterSymbol> parameters = default, NullableAnnotation nullableAnnotation = NullableAnnotation.None) { var invokeMethod = CreateMethodSymbol( attributes: default, accessibility: Accessibility.Public, modifiers: new DeclarationModifiers(), returnType: returnType, refKind: refKind, explicitInterfaceImplementations: default, name: "Invoke", typeParameters: default, parameters: parameters); return new CodeGenerationNamedTypeSymbol( containingAssembly: null, containingType: null, attributes: attributes, declaredAccessibility: accessibility, modifiers: modifiers, isRecord: false, typeKind: TypeKind.Delegate, name: name, typeParameters: typeParameters, baseType: null, interfaces: default, specialType: SpecialType.None, members: ImmutableArray.Create<ISymbol>(invokeMethod), typeMembers: ImmutableArray<CodeGenerationAbstractNamedTypeSymbol>.Empty, nullableAnnotation: nullableAnnotation, enumUnderlyingType: null); } /// <summary> /// Creates a namespace symbol that can be used to describe a namespace declaration. /// </summary> public static INamespaceSymbol CreateNamespaceSymbol(string name, IList<ISymbol>? imports = null, IList<INamespaceOrTypeSymbol>? members = null) { var @namespace = new CodeGenerationNamespaceSymbol(name, members); CodeGenerationNamespaceInfo.Attach(@namespace, imports); return @namespace; } internal static IMethodSymbol CreateMethodSymbol( IMethodSymbol method, ImmutableArray<AttributeData> attributes = default, Accessibility? accessibility = null, DeclarationModifiers? modifiers = null, ImmutableArray<IMethodSymbol> explicitInterfaceImplementations = default, string? name = null, ImmutableArray<IParameterSymbol>? parameters = null, ImmutableArray<SyntaxNode> statements = default, INamedTypeSymbol? containingType = null, ITypeSymbol? returnType = null, Optional<ImmutableArray<AttributeData>> returnTypeAttributes = default) { return CreateMethodSymbol( containingType, attributes, accessibility ?? method.DeclaredAccessibility, modifiers ?? method.GetSymbolModifiers(), returnType ?? method.ReturnType, method.RefKind, explicitInterfaceImplementations, name ?? method.Name, method.TypeParameters, parameters ?? method.Parameters, statements, returnTypeAttributes: returnTypeAttributes.HasValue ? returnTypeAttributes.Value : method.GetReturnTypeAttributes(), methodKind: method.MethodKind, isInitOnly: method.IsInitOnly); } internal static IPropertySymbol CreatePropertySymbol( IPropertySymbol property, ImmutableArray<AttributeData> attributes = default, ImmutableArray<IParameterSymbol>? parameters = null, Accessibility? accessibility = null, DeclarationModifiers? modifiers = null, ImmutableArray<IPropertySymbol> explicitInterfaceImplementations = default, string? name = null, bool? isIndexer = null, IMethodSymbol? getMethod = null, IMethodSymbol? setMethod = null) { return CreatePropertySymbol( attributes, accessibility ?? property.DeclaredAccessibility, modifiers ?? property.GetSymbolModifiers(), property.Type, property.RefKind, explicitInterfaceImplementations, name ?? property.Name, parameters ?? property.Parameters, getMethod, setMethod, isIndexer ?? property.IsIndexer); } internal static IEventSymbol CreateEventSymbol( IEventSymbol @event, ImmutableArray<AttributeData> attributes = default, Accessibility? accessibility = null, DeclarationModifiers? modifiers = null, ImmutableArray<IEventSymbol> explicitInterfaceImplementations = default, string? name = null, IMethodSymbol? addMethod = null, IMethodSymbol? removeMethod = null) { return CreateEventSymbol( attributes, accessibility ?? @event.DeclaredAccessibility, modifiers ?? @event.GetSymbolModifiers(), @event.Type, explicitInterfaceImplementations, name ?? @event.Name, addMethod, removeMethod); } } }
-1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/Compilers/VisualBasic/Test/Emit/ExpressionTrees/Results/CheckedAndUncheckedNothingConversions.txt
-=-=-=-=-=-=-=-=- Nothing -> SByte -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.SByte ) } return type: System.SByte type: System.Func`1[System.SByte] ) -=-=-=-=-=-=-=-=- CType(Nothing, SByte) -> SByte -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.SByte ) } return type: System.SByte type: System.Func`1[System.SByte] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, SByte) -> SByte -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.SByte ) } return type: System.SByte type: System.Func`1[System.SByte] ) -=-=-=-=-=-=-=-=- Nothing -> SByte? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`1[System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- CType(Nothing, SByte?) -> SByte? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`1[System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, SByte?) -> SByte? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`1[System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- Nothing -> E_SByte -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_SByte ) } return type: E_SByte type: System.Func`1[E_SByte] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_SByte) -> E_SByte -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_SByte ) } return type: E_SByte type: System.Func`1[E_SByte] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_SByte) -> E_SByte -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_SByte ) } return type: E_SByte type: System.Func`1[E_SByte] ) -=-=-=-=-=-=-=-=- Nothing -> E_SByte? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`1[System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_SByte?) -> E_SByte? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`1[System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_SByte?) -> E_SByte? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`1[System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- Nothing -> Byte -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Byte ) } return type: System.Byte type: System.Func`1[System.Byte] ) -=-=-=-=-=-=-=-=- CType(Nothing, Byte) -> Byte -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Byte ) } return type: System.Byte type: System.Func`1[System.Byte] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Byte) -> Byte -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Byte ) } return type: System.Byte type: System.Func`1[System.Byte] ) -=-=-=-=-=-=-=-=- Nothing -> Byte? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`1[System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- CType(Nothing, Byte?) -> Byte? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`1[System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Byte?) -> Byte? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`1[System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- Nothing -> E_Byte -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_Byte ) } return type: E_Byte type: System.Func`1[E_Byte] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_Byte) -> E_Byte -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_Byte ) } return type: E_Byte type: System.Func`1[E_Byte] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_Byte) -> E_Byte -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_Byte ) } return type: E_Byte type: System.Func`1[E_Byte] ) -=-=-=-=-=-=-=-=- Nothing -> E_Byte? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`1[System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_Byte?) -> E_Byte? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`1[System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_Byte?) -> E_Byte? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`1[System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- Nothing -> Short -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Int16 ) } return type: System.Int16 type: System.Func`1[System.Int16] ) -=-=-=-=-=-=-=-=- CType(Nothing, Short) -> Short -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Int16 ) } return type: System.Int16 type: System.Func`1[System.Int16] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Short) -> Short -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Int16 ) } return type: System.Int16 type: System.Func`1[System.Int16] ) -=-=-=-=-=-=-=-=- Nothing -> Short? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`1[System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- CType(Nothing, Short?) -> Short? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`1[System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Short?) -> Short? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`1[System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- Nothing -> E_Short -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_Short ) } return type: E_Short type: System.Func`1[E_Short] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_Short) -> E_Short -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_Short ) } return type: E_Short type: System.Func`1[E_Short] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_Short) -> E_Short -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_Short ) } return type: E_Short type: System.Func`1[E_Short] ) -=-=-=-=-=-=-=-=- Nothing -> E_Short? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`1[System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_Short?) -> E_Short? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`1[System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_Short?) -> E_Short? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`1[System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- Nothing -> UShort -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.UInt16 ) } return type: System.UInt16 type: System.Func`1[System.UInt16] ) -=-=-=-=-=-=-=-=- CType(Nothing, UShort) -> UShort -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.UInt16 ) } return type: System.UInt16 type: System.Func`1[System.UInt16] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, UShort) -> UShort -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.UInt16 ) } return type: System.UInt16 type: System.Func`1[System.UInt16] ) -=-=-=-=-=-=-=-=- Nothing -> UShort? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`1[System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- CType(Nothing, UShort?) -> UShort? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`1[System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, UShort?) -> UShort? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`1[System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- Nothing -> E_UShort -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_UShort ) } return type: E_UShort type: System.Func`1[E_UShort] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_UShort) -> E_UShort -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_UShort ) } return type: E_UShort type: System.Func`1[E_UShort] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_UShort) -> E_UShort -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_UShort ) } return type: E_UShort type: System.Func`1[E_UShort] ) -=-=-=-=-=-=-=-=- Nothing -> E_UShort? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`1[System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_UShort?) -> E_UShort? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`1[System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_UShort?) -> E_UShort? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`1[System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- Nothing -> Integer -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Int32 ) } return type: System.Int32 type: System.Func`1[System.Int32] ) -=-=-=-=-=-=-=-=- CType(Nothing, Integer) -> Integer -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Int32 ) } return type: System.Int32 type: System.Func`1[System.Int32] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Integer) -> Integer -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Int32 ) } return type: System.Int32 type: System.Func`1[System.Int32] ) -=-=-=-=-=-=-=-=- Nothing -> Integer? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`1[System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- CType(Nothing, Integer?) -> Integer? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`1[System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Integer?) -> Integer? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`1[System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- Nothing -> E_Integer -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_Integer ) } return type: E_Integer type: System.Func`1[E_Integer] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_Integer) -> E_Integer -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_Integer ) } return type: E_Integer type: System.Func`1[E_Integer] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_Integer) -> E_Integer -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_Integer ) } return type: E_Integer type: System.Func`1[E_Integer] ) -=-=-=-=-=-=-=-=- Nothing -> E_Integer? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`1[System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_Integer?) -> E_Integer? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`1[System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_Integer?) -> E_Integer? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`1[System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- Nothing -> UInteger -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.UInt32 ) } return type: System.UInt32 type: System.Func`1[System.UInt32] ) -=-=-=-=-=-=-=-=- CType(Nothing, UInteger) -> UInteger -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.UInt32 ) } return type: System.UInt32 type: System.Func`1[System.UInt32] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, UInteger) -> UInteger -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.UInt32 ) } return type: System.UInt32 type: System.Func`1[System.UInt32] ) -=-=-=-=-=-=-=-=- Nothing -> UInteger? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`1[System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- CType(Nothing, UInteger?) -> UInteger? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`1[System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, UInteger?) -> UInteger? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`1[System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- Nothing -> E_UInteger -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_UInteger ) } return type: E_UInteger type: System.Func`1[E_UInteger] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_UInteger) -> E_UInteger -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_UInteger ) } return type: E_UInteger type: System.Func`1[E_UInteger] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_UInteger) -> E_UInteger -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_UInteger ) } return type: E_UInteger type: System.Func`1[E_UInteger] ) -=-=-=-=-=-=-=-=- Nothing -> E_UInteger? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`1[System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_UInteger?) -> E_UInteger? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`1[System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_UInteger?) -> E_UInteger? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`1[System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- Nothing -> Long -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Int64 ) } return type: System.Int64 type: System.Func`1[System.Int64] ) -=-=-=-=-=-=-=-=- CType(Nothing, Long) -> Long -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Int64 ) } return type: System.Int64 type: System.Func`1[System.Int64] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Long) -> Long -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Int64 ) } return type: System.Int64 type: System.Func`1[System.Int64] ) -=-=-=-=-=-=-=-=- Nothing -> Long? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`1[System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- CType(Nothing, Long?) -> Long? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`1[System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Long?) -> Long? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`1[System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- Nothing -> E_Long -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_Long ) } return type: E_Long type: System.Func`1[E_Long] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_Long) -> E_Long -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_Long ) } return type: E_Long type: System.Func`1[E_Long] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_Long) -> E_Long -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_Long ) } return type: E_Long type: System.Func`1[E_Long] ) -=-=-=-=-=-=-=-=- Nothing -> E_Long? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`1[System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_Long?) -> E_Long? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`1[System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_Long?) -> E_Long? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`1[System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- Nothing -> Boolean -=-=-=-=-=-=-=-=- Lambda( body { Constant( False type: System.Boolean ) } return type: System.Boolean type: System.Func`1[System.Boolean] ) -=-=-=-=-=-=-=-=- CType(Nothing, Boolean) -> Boolean -=-=-=-=-=-=-=-=- Lambda( body { Constant( False type: System.Boolean ) } return type: System.Boolean type: System.Func`1[System.Boolean] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Boolean) -> Boolean -=-=-=-=-=-=-=-=- Lambda( body { Constant( False type: System.Boolean ) } return type: System.Boolean type: System.Func`1[System.Boolean] ) -=-=-=-=-=-=-=-=- Nothing -> Boolean? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`1[System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- CType(Nothing, Boolean?) -> Boolean? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`1[System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Boolean?) -> Boolean? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`1[System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- Nothing -> Single -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Single ) } return type: System.Single type: System.Func`1[System.Single] ) -=-=-=-=-=-=-=-=- CType(Nothing, Single) -> Single -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Single ) } return type: System.Single type: System.Func`1[System.Single] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Single) -> Single -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Single ) } return type: System.Single type: System.Func`1[System.Single] ) -=-=-=-=-=-=-=-=- Nothing -> Single? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`1[System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- CType(Nothing, Single?) -> Single? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`1[System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Single?) -> Single? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`1[System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- Nothing -> Double -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Double ) } return type: System.Double type: System.Func`1[System.Double] ) -=-=-=-=-=-=-=-=- CType(Nothing, Double) -> Double -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Double ) } return type: System.Double type: System.Func`1[System.Double] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Double) -> Double -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Double ) } return type: System.Double type: System.Func`1[System.Double] ) -=-=-=-=-=-=-=-=- Nothing -> Double? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`1[System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- CType(Nothing, Double?) -> Double? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`1[System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Double?) -> Double? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`1[System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- Nothing -> Decimal -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Decimal ) } return type: System.Decimal type: System.Func`1[System.Decimal] ) -=-=-=-=-=-=-=-=- CType(Nothing, Decimal) -> Decimal -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Decimal ) } return type: System.Decimal type: System.Func`1[System.Decimal] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Decimal) -> Decimal -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Decimal ) } return type: System.Decimal type: System.Func`1[System.Decimal] ) -=-=-=-=-=-=-=-=- Nothing -> Decimal? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`1[System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- CType(Nothing, Decimal?) -> Decimal? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`1[System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Decimal?) -> Decimal? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`1[System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- Nothing -> String -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.String ) } return type: System.String type: System.Func`1[System.String] ) -=-=-=-=-=-=-=-=- CType(Nothing, String) -> String -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.String ) } return type: System.String type: System.Func`1[System.String] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, String) -> String -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.String ) } return type: System.String type: System.Func`1[System.String] ) -=-=-=-=-=-=-=-=- Nothing -> Object -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) -=-=-=-=-=-=-=-=- CType(Nothing, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) -=-=-=-=-=-=-=-=- Nothing -> Clazz1 -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: Clazz1 ) } return type: Clazz1 type: System.Func`1[Clazz1] ) -=-=-=-=-=-=-=-=- CType(Nothing, Clazz1) -> Clazz1 -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: Clazz1 ) } return type: Clazz1 type: System.Func`1[Clazz1] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Clazz1) -> Clazz1 -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: Clazz1 ) } return type: Clazz1 type: System.Func`1[Clazz1] ) -=-=-=-=-=-=-=-=- Nothing -> Struct1 -=-=-=-=-=-=-=-=- Lambda( body { New( <.ctor>( ) type: Struct1 ) } return type: Struct1 type: System.Func`1[Struct1] ) -=-=-=-=-=-=-=-=- CType(Nothing, Struct1) -> Struct1 -=-=-=-=-=-=-=-=- Lambda( body { New( <.ctor>( ) type: Struct1 ) } return type: Struct1 type: System.Func`1[Struct1] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Struct1) -> Struct1 -=-=-=-=-=-=-=-=- Lambda( body { New( <.ctor>( ) type: Struct1 ) } return type: Struct1 type: System.Func`1[Struct1] ) -=-=-=-=-=-=-=-=- Nothing -> Clazz2(Of Clazz1, String) -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: Clazz2`2[Clazz1,System.String] ) } return type: Clazz2`2[Clazz1,System.String] type: System.Func`1[Clazz2`2[Clazz1,System.String]] ) -=-=-=-=-=-=-=-=- CType(Nothing, Clazz2(Of Clazz1, String)) -> Clazz2(Of Clazz1, String) -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: Clazz2`2[Clazz1,System.String] ) } return type: Clazz2`2[Clazz1,System.String] type: System.Func`1[Clazz2`2[Clazz1,System.String]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Clazz2(Of Clazz1, String)) -> Clazz2(Of Clazz1, String) -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: Clazz2`2[Clazz1,System.String] ) } return type: Clazz2`2[Clazz1,System.String] type: System.Func`1[Clazz2`2[Clazz1,System.String]] ) -=-=-=-=-=-=-=-=- Nothing -> Struct2(Of Struct1) -=-=-=-=-=-=-=-=- Lambda( body { New( <.ctor>( ) type: Struct2`1[Struct1] ) } return type: Struct2`1[Struct1] type: System.Func`1[Struct2`1[Struct1]] ) -=-=-=-=-=-=-=-=- CType(Nothing, Struct2(Of Struct1)) -> Struct2(Of Struct1) -=-=-=-=-=-=-=-=- Lambda( body { New( <.ctor>( ) type: Struct2`1[Struct1] ) } return type: Struct2`1[Struct1] type: System.Func`1[Struct2`1[Struct1]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Struct2(Of Struct1)) -> Struct2(Of Struct1) -=-=-=-=-=-=-=-=- Lambda( body { New( <.ctor>( ) type: Struct2`1[Struct1] ) } return type: Struct2`1[Struct1] type: System.Func`1[Struct2`1[Struct1]] ) -=-=-=-=-=-=-=-=- TryCast(Nothing, String) -> String -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.String ) } return type: System.String type: System.Func`1[System.String] ) -=-=-=-=-=-=-=-=- TryCast(Nothing, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) -=-=-=-=-=-=-=-=- TryCast(Nothing, Clazz1) -> Clazz1 -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: Clazz1 ) } return type: Clazz1 type: System.Func`1[Clazz1] ) -=-=-=-=-=-=-=-=- TryCast(Nothing, Clazz2(Of Clazz1, String)) -> Clazz2(Of Clazz1, String) -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: Clazz2`2[Clazz1,System.String] ) } return type: Clazz2`2[Clazz1,System.String] type: System.Func`1[Clazz2`2[Clazz1,System.String]] )
-=-=-=-=-=-=-=-=- Nothing -> SByte -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.SByte ) } return type: System.SByte type: System.Func`1[System.SByte] ) -=-=-=-=-=-=-=-=- CType(Nothing, SByte) -> SByte -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.SByte ) } return type: System.SByte type: System.Func`1[System.SByte] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, SByte) -> SByte -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.SByte ) } return type: System.SByte type: System.Func`1[System.SByte] ) -=-=-=-=-=-=-=-=- Nothing -> SByte? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`1[System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- CType(Nothing, SByte?) -> SByte? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`1[System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, SByte?) -> SByte? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`1[System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- Nothing -> E_SByte -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_SByte ) } return type: E_SByte type: System.Func`1[E_SByte] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_SByte) -> E_SByte -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_SByte ) } return type: E_SByte type: System.Func`1[E_SByte] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_SByte) -> E_SByte -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_SByte ) } return type: E_SByte type: System.Func`1[E_SByte] ) -=-=-=-=-=-=-=-=- Nothing -> E_SByte? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`1[System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_SByte?) -> E_SByte? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`1[System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_SByte?) -> E_SByte? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`1[System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- Nothing -> Byte -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Byte ) } return type: System.Byte type: System.Func`1[System.Byte] ) -=-=-=-=-=-=-=-=- CType(Nothing, Byte) -> Byte -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Byte ) } return type: System.Byte type: System.Func`1[System.Byte] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Byte) -> Byte -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Byte ) } return type: System.Byte type: System.Func`1[System.Byte] ) -=-=-=-=-=-=-=-=- Nothing -> Byte? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`1[System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- CType(Nothing, Byte?) -> Byte? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`1[System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Byte?) -> Byte? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`1[System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- Nothing -> E_Byte -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_Byte ) } return type: E_Byte type: System.Func`1[E_Byte] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_Byte) -> E_Byte -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_Byte ) } return type: E_Byte type: System.Func`1[E_Byte] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_Byte) -> E_Byte -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_Byte ) } return type: E_Byte type: System.Func`1[E_Byte] ) -=-=-=-=-=-=-=-=- Nothing -> E_Byte? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`1[System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_Byte?) -> E_Byte? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`1[System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_Byte?) -> E_Byte? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`1[System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- Nothing -> Short -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Int16 ) } return type: System.Int16 type: System.Func`1[System.Int16] ) -=-=-=-=-=-=-=-=- CType(Nothing, Short) -> Short -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Int16 ) } return type: System.Int16 type: System.Func`1[System.Int16] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Short) -> Short -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Int16 ) } return type: System.Int16 type: System.Func`1[System.Int16] ) -=-=-=-=-=-=-=-=- Nothing -> Short? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`1[System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- CType(Nothing, Short?) -> Short? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`1[System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Short?) -> Short? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`1[System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- Nothing -> E_Short -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_Short ) } return type: E_Short type: System.Func`1[E_Short] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_Short) -> E_Short -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_Short ) } return type: E_Short type: System.Func`1[E_Short] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_Short) -> E_Short -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_Short ) } return type: E_Short type: System.Func`1[E_Short] ) -=-=-=-=-=-=-=-=- Nothing -> E_Short? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`1[System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_Short?) -> E_Short? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`1[System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_Short?) -> E_Short? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`1[System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- Nothing -> UShort -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.UInt16 ) } return type: System.UInt16 type: System.Func`1[System.UInt16] ) -=-=-=-=-=-=-=-=- CType(Nothing, UShort) -> UShort -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.UInt16 ) } return type: System.UInt16 type: System.Func`1[System.UInt16] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, UShort) -> UShort -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.UInt16 ) } return type: System.UInt16 type: System.Func`1[System.UInt16] ) -=-=-=-=-=-=-=-=- Nothing -> UShort? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`1[System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- CType(Nothing, UShort?) -> UShort? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`1[System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, UShort?) -> UShort? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`1[System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- Nothing -> E_UShort -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_UShort ) } return type: E_UShort type: System.Func`1[E_UShort] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_UShort) -> E_UShort -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_UShort ) } return type: E_UShort type: System.Func`1[E_UShort] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_UShort) -> E_UShort -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_UShort ) } return type: E_UShort type: System.Func`1[E_UShort] ) -=-=-=-=-=-=-=-=- Nothing -> E_UShort? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`1[System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_UShort?) -> E_UShort? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`1[System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_UShort?) -> E_UShort? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`1[System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- Nothing -> Integer -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Int32 ) } return type: System.Int32 type: System.Func`1[System.Int32] ) -=-=-=-=-=-=-=-=- CType(Nothing, Integer) -> Integer -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Int32 ) } return type: System.Int32 type: System.Func`1[System.Int32] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Integer) -> Integer -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Int32 ) } return type: System.Int32 type: System.Func`1[System.Int32] ) -=-=-=-=-=-=-=-=- Nothing -> Integer? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`1[System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- CType(Nothing, Integer?) -> Integer? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`1[System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Integer?) -> Integer? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`1[System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- Nothing -> E_Integer -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_Integer ) } return type: E_Integer type: System.Func`1[E_Integer] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_Integer) -> E_Integer -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_Integer ) } return type: E_Integer type: System.Func`1[E_Integer] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_Integer) -> E_Integer -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_Integer ) } return type: E_Integer type: System.Func`1[E_Integer] ) -=-=-=-=-=-=-=-=- Nothing -> E_Integer? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`1[System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_Integer?) -> E_Integer? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`1[System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_Integer?) -> E_Integer? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`1[System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- Nothing -> UInteger -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.UInt32 ) } return type: System.UInt32 type: System.Func`1[System.UInt32] ) -=-=-=-=-=-=-=-=- CType(Nothing, UInteger) -> UInteger -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.UInt32 ) } return type: System.UInt32 type: System.Func`1[System.UInt32] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, UInteger) -> UInteger -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.UInt32 ) } return type: System.UInt32 type: System.Func`1[System.UInt32] ) -=-=-=-=-=-=-=-=- Nothing -> UInteger? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`1[System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- CType(Nothing, UInteger?) -> UInteger? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`1[System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, UInteger?) -> UInteger? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`1[System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- Nothing -> E_UInteger -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_UInteger ) } return type: E_UInteger type: System.Func`1[E_UInteger] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_UInteger) -> E_UInteger -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_UInteger ) } return type: E_UInteger type: System.Func`1[E_UInteger] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_UInteger) -> E_UInteger -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_UInteger ) } return type: E_UInteger type: System.Func`1[E_UInteger] ) -=-=-=-=-=-=-=-=- Nothing -> E_UInteger? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`1[System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_UInteger?) -> E_UInteger? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`1[System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_UInteger?) -> E_UInteger? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`1[System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- Nothing -> Long -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Int64 ) } return type: System.Int64 type: System.Func`1[System.Int64] ) -=-=-=-=-=-=-=-=- CType(Nothing, Long) -> Long -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Int64 ) } return type: System.Int64 type: System.Func`1[System.Int64] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Long) -> Long -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Int64 ) } return type: System.Int64 type: System.Func`1[System.Int64] ) -=-=-=-=-=-=-=-=- Nothing -> Long? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`1[System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- CType(Nothing, Long?) -> Long? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`1[System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Long?) -> Long? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`1[System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- Nothing -> E_Long -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_Long ) } return type: E_Long type: System.Func`1[E_Long] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_Long) -> E_Long -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_Long ) } return type: E_Long type: System.Func`1[E_Long] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_Long) -> E_Long -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_Long ) } return type: E_Long type: System.Func`1[E_Long] ) -=-=-=-=-=-=-=-=- Nothing -> E_Long? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`1[System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_Long?) -> E_Long? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`1[System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_Long?) -> E_Long? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`1[System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- Nothing -> Boolean -=-=-=-=-=-=-=-=- Lambda( body { Constant( False type: System.Boolean ) } return type: System.Boolean type: System.Func`1[System.Boolean] ) -=-=-=-=-=-=-=-=- CType(Nothing, Boolean) -> Boolean -=-=-=-=-=-=-=-=- Lambda( body { Constant( False type: System.Boolean ) } return type: System.Boolean type: System.Func`1[System.Boolean] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Boolean) -> Boolean -=-=-=-=-=-=-=-=- Lambda( body { Constant( False type: System.Boolean ) } return type: System.Boolean type: System.Func`1[System.Boolean] ) -=-=-=-=-=-=-=-=- Nothing -> Boolean? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`1[System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- CType(Nothing, Boolean?) -> Boolean? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`1[System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Boolean?) -> Boolean? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`1[System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- Nothing -> Single -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Single ) } return type: System.Single type: System.Func`1[System.Single] ) -=-=-=-=-=-=-=-=- CType(Nothing, Single) -> Single -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Single ) } return type: System.Single type: System.Func`1[System.Single] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Single) -> Single -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Single ) } return type: System.Single type: System.Func`1[System.Single] ) -=-=-=-=-=-=-=-=- Nothing -> Single? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`1[System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- CType(Nothing, Single?) -> Single? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`1[System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Single?) -> Single? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`1[System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- Nothing -> Double -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Double ) } return type: System.Double type: System.Func`1[System.Double] ) -=-=-=-=-=-=-=-=- CType(Nothing, Double) -> Double -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Double ) } return type: System.Double type: System.Func`1[System.Double] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Double) -> Double -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Double ) } return type: System.Double type: System.Func`1[System.Double] ) -=-=-=-=-=-=-=-=- Nothing -> Double? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`1[System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- CType(Nothing, Double?) -> Double? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`1[System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Double?) -> Double? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`1[System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- Nothing -> Decimal -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Decimal ) } return type: System.Decimal type: System.Func`1[System.Decimal] ) -=-=-=-=-=-=-=-=- CType(Nothing, Decimal) -> Decimal -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Decimal ) } return type: System.Decimal type: System.Func`1[System.Decimal] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Decimal) -> Decimal -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Decimal ) } return type: System.Decimal type: System.Func`1[System.Decimal] ) -=-=-=-=-=-=-=-=- Nothing -> Decimal? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`1[System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- CType(Nothing, Decimal?) -> Decimal? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`1[System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Decimal?) -> Decimal? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`1[System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- Nothing -> String -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.String ) } return type: System.String type: System.Func`1[System.String] ) -=-=-=-=-=-=-=-=- CType(Nothing, String) -> String -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.String ) } return type: System.String type: System.Func`1[System.String] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, String) -> String -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.String ) } return type: System.String type: System.Func`1[System.String] ) -=-=-=-=-=-=-=-=- Nothing -> Object -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) -=-=-=-=-=-=-=-=- CType(Nothing, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) -=-=-=-=-=-=-=-=- Nothing -> Clazz1 -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: Clazz1 ) } return type: Clazz1 type: System.Func`1[Clazz1] ) -=-=-=-=-=-=-=-=- CType(Nothing, Clazz1) -> Clazz1 -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: Clazz1 ) } return type: Clazz1 type: System.Func`1[Clazz1] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Clazz1) -> Clazz1 -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: Clazz1 ) } return type: Clazz1 type: System.Func`1[Clazz1] ) -=-=-=-=-=-=-=-=- Nothing -> Struct1 -=-=-=-=-=-=-=-=- Lambda( body { New( <.ctor>( ) type: Struct1 ) } return type: Struct1 type: System.Func`1[Struct1] ) -=-=-=-=-=-=-=-=- CType(Nothing, Struct1) -> Struct1 -=-=-=-=-=-=-=-=- Lambda( body { New( <.ctor>( ) type: Struct1 ) } return type: Struct1 type: System.Func`1[Struct1] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Struct1) -> Struct1 -=-=-=-=-=-=-=-=- Lambda( body { New( <.ctor>( ) type: Struct1 ) } return type: Struct1 type: System.Func`1[Struct1] ) -=-=-=-=-=-=-=-=- Nothing -> Clazz2(Of Clazz1, String) -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: Clazz2`2[Clazz1,System.String] ) } return type: Clazz2`2[Clazz1,System.String] type: System.Func`1[Clazz2`2[Clazz1,System.String]] ) -=-=-=-=-=-=-=-=- CType(Nothing, Clazz2(Of Clazz1, String)) -> Clazz2(Of Clazz1, String) -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: Clazz2`2[Clazz1,System.String] ) } return type: Clazz2`2[Clazz1,System.String] type: System.Func`1[Clazz2`2[Clazz1,System.String]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Clazz2(Of Clazz1, String)) -> Clazz2(Of Clazz1, String) -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: Clazz2`2[Clazz1,System.String] ) } return type: Clazz2`2[Clazz1,System.String] type: System.Func`1[Clazz2`2[Clazz1,System.String]] ) -=-=-=-=-=-=-=-=- Nothing -> Struct2(Of Struct1) -=-=-=-=-=-=-=-=- Lambda( body { New( <.ctor>( ) type: Struct2`1[Struct1] ) } return type: Struct2`1[Struct1] type: System.Func`1[Struct2`1[Struct1]] ) -=-=-=-=-=-=-=-=- CType(Nothing, Struct2(Of Struct1)) -> Struct2(Of Struct1) -=-=-=-=-=-=-=-=- Lambda( body { New( <.ctor>( ) type: Struct2`1[Struct1] ) } return type: Struct2`1[Struct1] type: System.Func`1[Struct2`1[Struct1]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Struct2(Of Struct1)) -> Struct2(Of Struct1) -=-=-=-=-=-=-=-=- Lambda( body { New( <.ctor>( ) type: Struct2`1[Struct1] ) } return type: Struct2`1[Struct1] type: System.Func`1[Struct2`1[Struct1]] ) -=-=-=-=-=-=-=-=- TryCast(Nothing, String) -> String -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.String ) } return type: System.String type: System.Func`1[System.String] ) -=-=-=-=-=-=-=-=- TryCast(Nothing, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) -=-=-=-=-=-=-=-=- TryCast(Nothing, Clazz1) -> Clazz1 -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: Clazz1 ) } return type: Clazz1 type: System.Func`1[Clazz1] ) -=-=-=-=-=-=-=-=- TryCast(Nothing, Clazz2(Of Clazz1, String)) -> Clazz2(Of Clazz1, String) -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: Clazz2`2[Clazz1,System.String] ) } return type: Clazz2`2[Clazz1,System.String] type: System.Func`1[Clazz2`2[Clazz1,System.String]] )
-1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmLanguage.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a // References\Debugger\v2.0\Microsoft.VisualStudio.Debugger.Engine.dll #endregion namespace Microsoft.VisualStudio.Debugger.Evaluation { public class DkmLanguage { public readonly DkmCompilerId Id; internal DkmLanguage(DkmCompilerId compilerId) { Id = compilerId; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a // References\Debugger\v2.0\Microsoft.VisualStudio.Debugger.Engine.dll #endregion namespace Microsoft.VisualStudio.Debugger.Evaluation { public class DkmLanguage { public readonly DkmCompilerId Id; internal DkmLanguage(DkmCompilerId compilerId) { Id = compilerId; } } }
-1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForConstructorsRefactoringTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.UseExpressionBody; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody { public class UseExpressionBodyForConstructorsRefactoringTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new UseExpressionBodyCodeRefactoringProvider(); private OptionsCollection UseExpressionBody => this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement); private OptionsCollection UseExpressionBodyDisabledDiagnostic => this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, new CodeStyleOption2<ExpressionBodyPreference>(ExpressionBodyPreference.WhenPossible, NotificationOption2.None)); private OptionsCollection UseBlockBody => this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, CSharpCodeStyleOptions.NeverWithSilentEnforcement); private OptionsCollection UseBlockBodyDisabledDiagnostic => this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, new CodeStyleOption2<ExpressionBodyPreference>(ExpressionBodyPreference.Never, NotificationOption2.None)); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestNotOfferedIfUserPrefersExpressionBodiesAndInBlockBody() { await TestMissingAsync( @"class C { public C() { [||]Bar(); } }", parameters: new TestParameters(options: UseExpressionBody)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferedIfUserPrefersExpressionBodiesWithoutDiagnosticAndInBlockBody() { await TestInRegularAndScript1Async( @"class C { public C() { [||]Bar(); } }", @"class C { public C() => Bar(); }", parameters: new TestParameters(options: UseExpressionBodyDisabledDiagnostic)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferedIfUserPrefersBlockBodiesAndInBlockBody() { await TestInRegularAndScript1Async( @"class C { public C() { [||]Bar(); } }", @"class C { public C() => Bar(); }", parameters: new TestParameters(options: UseBlockBody)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestNotOfferedInLambda() { await TestMissingAsync( @"class C { public C() { return () => { [||] }; } }", parameters: new TestParameters(options: UseBlockBody)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestNotOfferedIfUserPrefersBlockBodiesAndInExpressionBody() { await TestMissingAsync( @"class C { public C() => [||]Bar(); }", parameters: new TestParameters(options: UseBlockBody)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferedIfUserPrefersBlockBodiesWithoutDiagnosticAndInExpressionBody() { await TestInRegularAndScript1Async( @"class C { public C() => [||]Bar(); }", @"class C { public C() { Bar(); } }", parameters: new TestParameters(options: UseBlockBodyDisabledDiagnostic)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferedIfUserPrefersExpressionBodiesAndInExpressionBody() { await TestInRegularAndScript1Async( @"class C { public C() => [||]Bar(); }", @"class C { public C() { Bar(); } }", parameters: new TestParameters(options: UseExpressionBody)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.UseExpressionBody; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody { public class UseExpressionBodyForConstructorsRefactoringTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new UseExpressionBodyCodeRefactoringProvider(); private OptionsCollection UseExpressionBody => this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement); private OptionsCollection UseExpressionBodyDisabledDiagnostic => this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, new CodeStyleOption2<ExpressionBodyPreference>(ExpressionBodyPreference.WhenPossible, NotificationOption2.None)); private OptionsCollection UseBlockBody => this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, CSharpCodeStyleOptions.NeverWithSilentEnforcement); private OptionsCollection UseBlockBodyDisabledDiagnostic => this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, new CodeStyleOption2<ExpressionBodyPreference>(ExpressionBodyPreference.Never, NotificationOption2.None)); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestNotOfferedIfUserPrefersExpressionBodiesAndInBlockBody() { await TestMissingAsync( @"class C { public C() { [||]Bar(); } }", parameters: new TestParameters(options: UseExpressionBody)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferedIfUserPrefersExpressionBodiesWithoutDiagnosticAndInBlockBody() { await TestInRegularAndScript1Async( @"class C { public C() { [||]Bar(); } }", @"class C { public C() => Bar(); }", parameters: new TestParameters(options: UseExpressionBodyDisabledDiagnostic)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferedIfUserPrefersBlockBodiesAndInBlockBody() { await TestInRegularAndScript1Async( @"class C { public C() { [||]Bar(); } }", @"class C { public C() => Bar(); }", parameters: new TestParameters(options: UseBlockBody)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestNotOfferedInLambda() { await TestMissingAsync( @"class C { public C() { return () => { [||] }; } }", parameters: new TestParameters(options: UseBlockBody)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestNotOfferedIfUserPrefersBlockBodiesAndInExpressionBody() { await TestMissingAsync( @"class C { public C() => [||]Bar(); }", parameters: new TestParameters(options: UseBlockBody)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferedIfUserPrefersBlockBodiesWithoutDiagnosticAndInExpressionBody() { await TestInRegularAndScript1Async( @"class C { public C() => [||]Bar(); }", @"class C { public C() { Bar(); } }", parameters: new TestParameters(options: UseBlockBodyDisabledDiagnostic)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestOfferedIfUserPrefersExpressionBodiesAndInExpressionBody() { await TestInRegularAndScript1Async( @"class C { public C() => [||]Bar(); }", @"class C { public C() { Bar(); } }", parameters: new TestParameters(options: UseExpressionBody)); } } }
-1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/Features/Core/Portable/PullMemberUp/Dialog/PullMemberUpWithDialogCodeAction.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings.PullMemberUp.Dialog; using Microsoft.CodeAnalysis.PullMemberUp; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeRefactorings.PullMemberUp { internal abstract partial class AbstractPullMemberUpRefactoringProvider { private class PullMemberUpWithDialogCodeAction : CodeActionWithOptions { /// <summary> /// Member which user initially selects. It will be selected initially when the dialog pops up. /// </summary> private readonly ISymbol _selectedMember; private readonly Document _document; private readonly IPullMemberUpOptionsService _service; public override string Title => FeaturesResources.Pull_members_up_to_base_type; public PullMemberUpWithDialogCodeAction( Document document, ISymbol selectedMember, IPullMemberUpOptionsService service) { _document = document; _selectedMember = selectedMember; _service = service; } public override object GetOptions(CancellationToken cancellationToken) { var pullMemberUpOptionService = _service ?? _document.Project.Solution.Workspace.Services.GetRequiredService<IPullMemberUpOptionsService>(); return pullMemberUpOptionService.GetPullMemberUpOptions(_document, _selectedMember); } protected override async Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync(object options, CancellationToken cancellationToken) { if (options is PullMembersUpOptions pullMemberUpOptions) { var changedSolution = await MembersPuller.PullMembersUpAsync(_document, pullMemberUpOptions, cancellationToken).ConfigureAwait(false); return new[] { new ApplyChangesOperation(changedSolution) }; } else { // If user click cancel button, options will be null and hit this branch return SpecializedCollections.EmptyEnumerable<CodeActionOperation>(); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings.PullMemberUp.Dialog; using Microsoft.CodeAnalysis.PullMemberUp; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeRefactorings.PullMemberUp { internal abstract partial class AbstractPullMemberUpRefactoringProvider { private class PullMemberUpWithDialogCodeAction : CodeActionWithOptions { /// <summary> /// Member which user initially selects. It will be selected initially when the dialog pops up. /// </summary> private readonly ISymbol _selectedMember; private readonly Document _document; private readonly IPullMemberUpOptionsService _service; public override string Title => FeaturesResources.Pull_members_up_to_base_type; public PullMemberUpWithDialogCodeAction( Document document, ISymbol selectedMember, IPullMemberUpOptionsService service) { _document = document; _selectedMember = selectedMember; _service = service; } public override object GetOptions(CancellationToken cancellationToken) { var pullMemberUpOptionService = _service ?? _document.Project.Solution.Workspace.Services.GetRequiredService<IPullMemberUpOptionsService>(); return pullMemberUpOptionService.GetPullMemberUpOptions(_document, _selectedMember); } protected override async Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync(object options, CancellationToken cancellationToken) { if (options is PullMembersUpOptions pullMemberUpOptions) { var changedSolution = await MembersPuller.PullMembersUpAsync(_document, pullMemberUpOptions, cancellationToken).ConfigureAwait(false); return new[] { new ApplyChangesOperation(changedSolution) }; } else { // If user click cancel button, options will be null and hit this branch return SpecializedCollections.EmptyEnumerable<CodeActionOperation>(); } } } } }
-1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/Features/VisualBasic/Portable/Structure/VisualBasicBlockStructureService.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports Microsoft.CodeAnalysis.Host Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Structure Namespace Microsoft.CodeAnalysis.VisualBasic.Structure <ExportLanguageServiceFactory(GetType(BlockStructureService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicBlockStructureServiceFactory Implements ILanguageServiceFactory <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Function CreateLanguageService(languageServices As HostLanguageServices) As ILanguageService Implements ILanguageServiceFactory.CreateLanguageService Return New VisualBasicBlockStructureService(languageServices.WorkspaceServices.Workspace) End Function End Class Friend Class VisualBasicBlockStructureService Inherits BlockStructureServiceWithProviders Friend Sub New(workspace As Workspace) MyBase.New(workspace) End Sub Public Overrides ReadOnly Property Language As String Get Return LanguageNames.VisualBasic End Get End Property Protected Overrides Function GetBuiltInProviders() As ImmutableArray(Of BlockStructureProvider) Return ImmutableArray.Create(Of BlockStructureProvider)(New VisualBasicBlockStructureProvider()) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports Microsoft.CodeAnalysis.Host Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Structure Namespace Microsoft.CodeAnalysis.VisualBasic.Structure <ExportLanguageServiceFactory(GetType(BlockStructureService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicBlockStructureServiceFactory Implements ILanguageServiceFactory <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Function CreateLanguageService(languageServices As HostLanguageServices) As ILanguageService Implements ILanguageServiceFactory.CreateLanguageService Return New VisualBasicBlockStructureService(languageServices.WorkspaceServices.Workspace) End Function End Class Friend Class VisualBasicBlockStructureService Inherits BlockStructureServiceWithProviders Friend Sub New(workspace As Workspace) MyBase.New(workspace) End Sub Public Overrides ReadOnly Property Language As String Get Return LanguageNames.VisualBasic End Get End Property Protected Overrides Function GetBuiltInProviders() As ImmutableArray(Of BlockStructureProvider) Return ImmutableArray.Create(Of BlockStructureProvider)(New VisualBasicBlockStructureProvider()) End Function End Class End Namespace
-1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_SyncLock.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Diagnostics Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend NotInheritable Class LocalRewriter Public Overrides Function VisitSyncLockStatement(node As BoundSyncLockStatement) As BoundNode Dim statements = ArrayBuilder(Of BoundStatement).GetInstance Dim syntaxNode = DirectCast(node.Syntax, SyncLockBlockSyntax) ' rewrite the lock expression. Dim visitedLockExpression = VisitExpressionNode(node.LockExpression) Dim objectType = GetSpecialType(SpecialType.System_Object) Dim useSiteInfo = GetNewCompoundUseSiteInfo() Dim conversionKind = Conversions.ClassifyConversion(visitedLockExpression.Type, objectType, useSiteInfo).Key _diagnostics.Add(node, useSiteInfo) ' when passing this boundlocal to Monitor.Enter and Monitor.Exit we need to pass a local of type object, because the parameter ' are of type object. We also do not want to have this conversion being shown in the semantic model, which is why we add it ' during rewriting. Because only reference types are allowed for synclock, this is always guaranteed to succeed. ' This also unboxes a type parameter, so that the same object is passed to both methods. If Not Conversions.IsIdentityConversion(conversionKind) Then Dim integerOverflow As Boolean Dim constantResult = Conversions.TryFoldConstantConversion( visitedLockExpression, objectType, integerOverflow) visitedLockExpression = TransformRewrittenConversion(New BoundConversion(node.LockExpression.Syntax, visitedLockExpression, conversionKind, False, False, constantResult, objectType)) End If ' create a new temp local for the lock object Dim tempLockObjectLocal As LocalSymbol = New SynthesizedLocal(Me._currentMethodOrLambda, objectType, SynthesizedLocalKind.Lock, syntaxNode.SyncLockStatement) Dim boundLockObjectLocal = New BoundLocal(syntaxNode, tempLockObjectLocal, objectType) Dim instrument As Boolean = Me.Instrument(node) If instrument Then ' create a sequence point that contains the whole SyncLock statement as the first reachable sequence point ' of the SyncLock statement. Dim prologue = _instrumenterOpt.CreateSyncLockStatementPrologue(node) If prologue IsNot Nothing Then statements.Add(prologue) End If End If ' assign the lock expression / object to it to avoid changes to it Dim tempLockObjectAssignment As BoundStatement = New BoundAssignmentOperator(syntaxNode, boundLockObjectLocal, visitedLockExpression, suppressObjectClone:=True, type:=objectType).ToStatement boundLockObjectLocal = boundLockObjectLocal.MakeRValue() If ShouldGenerateUnstructuredExceptionHandlingResumeCode(node) Then tempLockObjectAssignment = RegisterUnstructuredExceptionHandlingResumeTarget(syntaxNode, tempLockObjectAssignment, canThrow:=True) End If Dim saveState As UnstructuredExceptionHandlingContext = LeaveUnstructuredExceptionHandlingContext(node) If instrument Then tempLockObjectAssignment = _instrumenterOpt.InstrumentSyncLockObjectCapture(node, tempLockObjectAssignment) End If statements.Add(tempLockObjectAssignment) ' If the type of the lock object is System.Object we need to call the vb runtime helper ' Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.CheckForSyncLockOnValueType to ensure no value type is ' used. Note that we are checking type on original bound node for LockExpression because rewritten node will ' always have System.Object as its type due to conversion added above. ' If helper not available on this platform (/vbruntime*), don't call this helper and do not report errors. Dim checkForSyncLockOnValueTypeMethod As MethodSymbol = Nothing If node.LockExpression.Type.IsObjectType() AndAlso TryGetWellknownMember(checkForSyncLockOnValueTypeMethod, WellKnownMember.Microsoft_VisualBasic_CompilerServices_ObjectFlowControl__CheckForSyncLockOnValueType, syntaxNode, isOptional:=True) Then Dim boundHelperCall = New BoundCall(syntaxNode, checkForSyncLockOnValueTypeMethod, Nothing, Nothing, ImmutableArray.Create(Of BoundExpression)(boundLockObjectLocal), Nothing, checkForSyncLockOnValueTypeMethod.ReturnType, suppressObjectClone:=True) Dim boundHelperCallStatement = boundHelperCall.ToStatement boundHelperCallStatement.SetWasCompilerGenerated() ' used to not create sequence points statements.Add(boundHelperCallStatement) End If Dim locals As ImmutableArray(Of LocalSymbol) Dim boundLockTakenLocal As BoundLocal = Nothing Dim tempLockTakenAssignment As BoundStatement = Nothing Dim tryStatements As ImmutableArray(Of BoundStatement) Dim boundMonitorEnterCallStatement As BoundStatement = GenerateMonitorEnter(node.LockExpression.Syntax, boundLockObjectLocal, boundLockTakenLocal, tempLockTakenAssignment) ' the new Monitor.Enter call will be inside the try block, the old is outside If boundLockTakenLocal IsNot Nothing Then locals = ImmutableArray.Create(Of LocalSymbol)(tempLockObjectLocal, boundLockTakenLocal.LocalSymbol) statements.Add(tempLockTakenAssignment) tryStatements = ImmutableArray.Create(Of BoundStatement)(boundMonitorEnterCallStatement, DirectCast(Visit(node.Body), BoundBlock)) Else locals = ImmutableArray.Create(tempLockObjectLocal) statements.Add(boundMonitorEnterCallStatement) tryStatements = ImmutableArray.Create(Of BoundStatement)(DirectCast(Visit(node.Body), BoundBlock)) End If ' rewrite the SyncLock body Dim tryBody As BoundBlock = New BoundBlock(syntaxNode, Nothing, ImmutableArray(Of LocalSymbol).Empty, tryStatements) Dim statementInFinally As BoundStatement = GenerateMonitorExit(syntaxNode, boundLockObjectLocal, boundLockTakenLocal) Dim finallyBody As BoundBlock = New BoundBlock(syntaxNode, Nothing, ImmutableArray(Of LocalSymbol).Empty, ImmutableArray.Create(Of BoundStatement)(statementInFinally)) If instrument Then ' Add a sequence point to highlight the "End SyncLock" syntax in case the body has thrown an exception finallyBody = DirectCast(Concat(finallyBody, _instrumenterOpt.CreateSyncLockExitDueToExceptionEpilogue(node)), BoundBlock) End If Dim rewrittenSyncLock = RewriteTryStatement(syntaxNode, tryBody, ImmutableArray(Of BoundCatchBlock).Empty, finallyBody, Nothing) statements.Add(rewrittenSyncLock) If instrument Then ' Add a sequence point to highlight the "End SyncLock" syntax in case the body has been complete executed and ' exited normally Dim epilogue = _instrumenterOpt.CreateSyncLockExitNormallyEpilogue(node) If epilogue IsNot Nothing Then statements.Add(epilogue) End If End If RestoreUnstructuredExceptionHandlingContext(node, saveState) Return New BoundBlock(syntaxNode, Nothing, locals, statements.ToImmutableAndFree) End Function Private Function GenerateMonitorEnter( syntaxNode As SyntaxNode, boundLockObject As BoundExpression, <Out> ByRef boundLockTakenLocal As BoundLocal, <Out> ByRef boundLockTakenInitialization As BoundStatement ) As BoundStatement boundLockTakenLocal = Nothing boundLockTakenInitialization = Nothing Dim parameters As ImmutableArray(Of BoundExpression) ' Figure out what Enter method to call from Monitor. ' In case the "new" Monitor.Enter(Object, ByRef Boolean) method is found, use that one, ' otherwise fall back to the Monitor.Enter() method. Dim enterMethod As MethodSymbol = Nothing If TryGetWellknownMember(enterMethod, WellKnownMember.System_Threading_Monitor__Enter2, syntaxNode, isOptional:=True) Then ' create local for the lockTaken boolean and initialize it with "False" Dim tempLockTaken As LocalSymbol If syntaxNode.Parent.Kind = SyntaxKind.SyncLockStatement Then tempLockTaken = New SynthesizedLocal(Me._currentMethodOrLambda, enterMethod.Parameters(1).Type, SynthesizedLocalKind.LockTaken, DirectCast(syntaxNode.Parent, SyncLockStatementSyntax)) Else tempLockTaken = New SynthesizedLocal(Me._currentMethodOrLambda, enterMethod.Parameters(1).Type, SynthesizedLocalKind.LoweringTemp) End If Debug.Assert(tempLockTaken.Type.IsBooleanType()) boundLockTakenLocal = New BoundLocal(syntaxNode, tempLockTaken, tempLockTaken.Type) boundLockTakenInitialization = New BoundAssignmentOperator(syntaxNode, boundLockTakenLocal, New BoundLiteral(syntaxNode, ConstantValue.False, boundLockTakenLocal.Type), suppressObjectClone:=True, type:=boundLockTakenLocal.Type).ToStatement boundLockTakenInitialization.SetWasCompilerGenerated() ' used to not create sequence points parameters = ImmutableArray.Create(Of BoundExpression)(boundLockObject, boundLockTakenLocal) boundLockTakenLocal = boundLockTakenLocal.MakeRValue() Else TryGetWellknownMember(enterMethod, WellKnownMember.System_Threading_Monitor__Enter, syntaxNode) parameters = ImmutableArray.Create(Of BoundExpression)(boundLockObject) End If If enterMethod IsNot Nothing Then ' create a call to void Enter(object) Dim boundMonitorEnterCall As BoundExpression boundMonitorEnterCall = New BoundCall(syntaxNode, enterMethod, Nothing, Nothing, parameters, Nothing, enterMethod.ReturnType, suppressObjectClone:=True) Dim boundMonitorEnterCallStatement = boundMonitorEnterCall.ToStatement boundMonitorEnterCallStatement.SetWasCompilerGenerated() ' used to not create sequence points Return boundMonitorEnterCallStatement End If Return New BoundBadExpression(syntaxNode, LookupResultKind.NotReferencable, ImmutableArray(Of Symbol).Empty, parameters, ErrorTypeSymbol.UnknownResultType, hasErrors:=True).ToStatement() End Function Private Function GenerateMonitorExit( syntaxNode As SyntaxNode, boundLockObject As BoundExpression, boundLockTakenLocal As BoundLocal ) As BoundStatement Dim statementInFinally As BoundStatement Dim boundMonitorExitCall As BoundExpression Dim exitMethod As MethodSymbol = Nothing If TryGetWellknownMember(exitMethod, WellKnownMember.System_Threading_Monitor__Exit, syntaxNode) Then ' create a call to void Monitor.Exit(object) boundMonitorExitCall = New BoundCall(syntaxNode, exitMethod, Nothing, Nothing, ImmutableArray.Create(Of BoundExpression)(boundLockObject), Nothing, exitMethod.ReturnType, suppressObjectClone:=True) Else boundMonitorExitCall = New BoundBadExpression(syntaxNode, LookupResultKind.NotReferencable, ImmutableArray(Of Symbol).Empty, ImmutableArray.Create(boundLockObject), ErrorTypeSymbol.UnknownResultType, hasErrors:=True) End If Dim boundMonitorExitCallStatement = boundMonitorExitCall.ToStatement boundMonitorExitCallStatement.SetWasCompilerGenerated() ' used to not create sequence points If boundLockTakenLocal IsNot Nothing Then Debug.Assert(boundLockTakenLocal.Type.IsBooleanType()) ' if the "new" enter method is used we need to check the temporary boolean to see if the lock was really taken. ' (maybe there was an exception after try and before the enter call). Dim boundCondition = New BoundBinaryOperator(syntaxNode, BinaryOperatorKind.Equals, boundLockTakenLocal, New BoundLiteral(syntaxNode, ConstantValue.True, boundLockTakenLocal.Type), False, boundLockTakenLocal.Type) statementInFinally = RewriteIfStatement(syntaxNode, boundCondition, boundMonitorExitCallStatement, Nothing, instrumentationTargetOpt:=Nothing) Else statementInFinally = boundMonitorExitCallStatement End If Return statementInFinally End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Diagnostics Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend NotInheritable Class LocalRewriter Public Overrides Function VisitSyncLockStatement(node As BoundSyncLockStatement) As BoundNode Dim statements = ArrayBuilder(Of BoundStatement).GetInstance Dim syntaxNode = DirectCast(node.Syntax, SyncLockBlockSyntax) ' rewrite the lock expression. Dim visitedLockExpression = VisitExpressionNode(node.LockExpression) Dim objectType = GetSpecialType(SpecialType.System_Object) Dim useSiteInfo = GetNewCompoundUseSiteInfo() Dim conversionKind = Conversions.ClassifyConversion(visitedLockExpression.Type, objectType, useSiteInfo).Key _diagnostics.Add(node, useSiteInfo) ' when passing this boundlocal to Monitor.Enter and Monitor.Exit we need to pass a local of type object, because the parameter ' are of type object. We also do not want to have this conversion being shown in the semantic model, which is why we add it ' during rewriting. Because only reference types are allowed for synclock, this is always guaranteed to succeed. ' This also unboxes a type parameter, so that the same object is passed to both methods. If Not Conversions.IsIdentityConversion(conversionKind) Then Dim integerOverflow As Boolean Dim constantResult = Conversions.TryFoldConstantConversion( visitedLockExpression, objectType, integerOverflow) visitedLockExpression = TransformRewrittenConversion(New BoundConversion(node.LockExpression.Syntax, visitedLockExpression, conversionKind, False, False, constantResult, objectType)) End If ' create a new temp local for the lock object Dim tempLockObjectLocal As LocalSymbol = New SynthesizedLocal(Me._currentMethodOrLambda, objectType, SynthesizedLocalKind.Lock, syntaxNode.SyncLockStatement) Dim boundLockObjectLocal = New BoundLocal(syntaxNode, tempLockObjectLocal, objectType) Dim instrument As Boolean = Me.Instrument(node) If instrument Then ' create a sequence point that contains the whole SyncLock statement as the first reachable sequence point ' of the SyncLock statement. Dim prologue = _instrumenterOpt.CreateSyncLockStatementPrologue(node) If prologue IsNot Nothing Then statements.Add(prologue) End If End If ' assign the lock expression / object to it to avoid changes to it Dim tempLockObjectAssignment As BoundStatement = New BoundAssignmentOperator(syntaxNode, boundLockObjectLocal, visitedLockExpression, suppressObjectClone:=True, type:=objectType).ToStatement boundLockObjectLocal = boundLockObjectLocal.MakeRValue() If ShouldGenerateUnstructuredExceptionHandlingResumeCode(node) Then tempLockObjectAssignment = RegisterUnstructuredExceptionHandlingResumeTarget(syntaxNode, tempLockObjectAssignment, canThrow:=True) End If Dim saveState As UnstructuredExceptionHandlingContext = LeaveUnstructuredExceptionHandlingContext(node) If instrument Then tempLockObjectAssignment = _instrumenterOpt.InstrumentSyncLockObjectCapture(node, tempLockObjectAssignment) End If statements.Add(tempLockObjectAssignment) ' If the type of the lock object is System.Object we need to call the vb runtime helper ' Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.CheckForSyncLockOnValueType to ensure no value type is ' used. Note that we are checking type on original bound node for LockExpression because rewritten node will ' always have System.Object as its type due to conversion added above. ' If helper not available on this platform (/vbruntime*), don't call this helper and do not report errors. Dim checkForSyncLockOnValueTypeMethod As MethodSymbol = Nothing If node.LockExpression.Type.IsObjectType() AndAlso TryGetWellknownMember(checkForSyncLockOnValueTypeMethod, WellKnownMember.Microsoft_VisualBasic_CompilerServices_ObjectFlowControl__CheckForSyncLockOnValueType, syntaxNode, isOptional:=True) Then Dim boundHelperCall = New BoundCall(syntaxNode, checkForSyncLockOnValueTypeMethod, Nothing, Nothing, ImmutableArray.Create(Of BoundExpression)(boundLockObjectLocal), Nothing, checkForSyncLockOnValueTypeMethod.ReturnType, suppressObjectClone:=True) Dim boundHelperCallStatement = boundHelperCall.ToStatement boundHelperCallStatement.SetWasCompilerGenerated() ' used to not create sequence points statements.Add(boundHelperCallStatement) End If Dim locals As ImmutableArray(Of LocalSymbol) Dim boundLockTakenLocal As BoundLocal = Nothing Dim tempLockTakenAssignment As BoundStatement = Nothing Dim tryStatements As ImmutableArray(Of BoundStatement) Dim boundMonitorEnterCallStatement As BoundStatement = GenerateMonitorEnter(node.LockExpression.Syntax, boundLockObjectLocal, boundLockTakenLocal, tempLockTakenAssignment) ' the new Monitor.Enter call will be inside the try block, the old is outside If boundLockTakenLocal IsNot Nothing Then locals = ImmutableArray.Create(Of LocalSymbol)(tempLockObjectLocal, boundLockTakenLocal.LocalSymbol) statements.Add(tempLockTakenAssignment) tryStatements = ImmutableArray.Create(Of BoundStatement)(boundMonitorEnterCallStatement, DirectCast(Visit(node.Body), BoundBlock)) Else locals = ImmutableArray.Create(tempLockObjectLocal) statements.Add(boundMonitorEnterCallStatement) tryStatements = ImmutableArray.Create(Of BoundStatement)(DirectCast(Visit(node.Body), BoundBlock)) End If ' rewrite the SyncLock body Dim tryBody As BoundBlock = New BoundBlock(syntaxNode, Nothing, ImmutableArray(Of LocalSymbol).Empty, tryStatements) Dim statementInFinally As BoundStatement = GenerateMonitorExit(syntaxNode, boundLockObjectLocal, boundLockTakenLocal) Dim finallyBody As BoundBlock = New BoundBlock(syntaxNode, Nothing, ImmutableArray(Of LocalSymbol).Empty, ImmutableArray.Create(Of BoundStatement)(statementInFinally)) If instrument Then ' Add a sequence point to highlight the "End SyncLock" syntax in case the body has thrown an exception finallyBody = DirectCast(Concat(finallyBody, _instrumenterOpt.CreateSyncLockExitDueToExceptionEpilogue(node)), BoundBlock) End If Dim rewrittenSyncLock = RewriteTryStatement(syntaxNode, tryBody, ImmutableArray(Of BoundCatchBlock).Empty, finallyBody, Nothing) statements.Add(rewrittenSyncLock) If instrument Then ' Add a sequence point to highlight the "End SyncLock" syntax in case the body has been complete executed and ' exited normally Dim epilogue = _instrumenterOpt.CreateSyncLockExitNormallyEpilogue(node) If epilogue IsNot Nothing Then statements.Add(epilogue) End If End If RestoreUnstructuredExceptionHandlingContext(node, saveState) Return New BoundBlock(syntaxNode, Nothing, locals, statements.ToImmutableAndFree) End Function Private Function GenerateMonitorEnter( syntaxNode As SyntaxNode, boundLockObject As BoundExpression, <Out> ByRef boundLockTakenLocal As BoundLocal, <Out> ByRef boundLockTakenInitialization As BoundStatement ) As BoundStatement boundLockTakenLocal = Nothing boundLockTakenInitialization = Nothing Dim parameters As ImmutableArray(Of BoundExpression) ' Figure out what Enter method to call from Monitor. ' In case the "new" Monitor.Enter(Object, ByRef Boolean) method is found, use that one, ' otherwise fall back to the Monitor.Enter() method. Dim enterMethod As MethodSymbol = Nothing If TryGetWellknownMember(enterMethod, WellKnownMember.System_Threading_Monitor__Enter2, syntaxNode, isOptional:=True) Then ' create local for the lockTaken boolean and initialize it with "False" Dim tempLockTaken As LocalSymbol If syntaxNode.Parent.Kind = SyntaxKind.SyncLockStatement Then tempLockTaken = New SynthesizedLocal(Me._currentMethodOrLambda, enterMethod.Parameters(1).Type, SynthesizedLocalKind.LockTaken, DirectCast(syntaxNode.Parent, SyncLockStatementSyntax)) Else tempLockTaken = New SynthesizedLocal(Me._currentMethodOrLambda, enterMethod.Parameters(1).Type, SynthesizedLocalKind.LoweringTemp) End If Debug.Assert(tempLockTaken.Type.IsBooleanType()) boundLockTakenLocal = New BoundLocal(syntaxNode, tempLockTaken, tempLockTaken.Type) boundLockTakenInitialization = New BoundAssignmentOperator(syntaxNode, boundLockTakenLocal, New BoundLiteral(syntaxNode, ConstantValue.False, boundLockTakenLocal.Type), suppressObjectClone:=True, type:=boundLockTakenLocal.Type).ToStatement boundLockTakenInitialization.SetWasCompilerGenerated() ' used to not create sequence points parameters = ImmutableArray.Create(Of BoundExpression)(boundLockObject, boundLockTakenLocal) boundLockTakenLocal = boundLockTakenLocal.MakeRValue() Else TryGetWellknownMember(enterMethod, WellKnownMember.System_Threading_Monitor__Enter, syntaxNode) parameters = ImmutableArray.Create(Of BoundExpression)(boundLockObject) End If If enterMethod IsNot Nothing Then ' create a call to void Enter(object) Dim boundMonitorEnterCall As BoundExpression boundMonitorEnterCall = New BoundCall(syntaxNode, enterMethod, Nothing, Nothing, parameters, Nothing, enterMethod.ReturnType, suppressObjectClone:=True) Dim boundMonitorEnterCallStatement = boundMonitorEnterCall.ToStatement boundMonitorEnterCallStatement.SetWasCompilerGenerated() ' used to not create sequence points Return boundMonitorEnterCallStatement End If Return New BoundBadExpression(syntaxNode, LookupResultKind.NotReferencable, ImmutableArray(Of Symbol).Empty, parameters, ErrorTypeSymbol.UnknownResultType, hasErrors:=True).ToStatement() End Function Private Function GenerateMonitorExit( syntaxNode As SyntaxNode, boundLockObject As BoundExpression, boundLockTakenLocal As BoundLocal ) As BoundStatement Dim statementInFinally As BoundStatement Dim boundMonitorExitCall As BoundExpression Dim exitMethod As MethodSymbol = Nothing If TryGetWellknownMember(exitMethod, WellKnownMember.System_Threading_Monitor__Exit, syntaxNode) Then ' create a call to void Monitor.Exit(object) boundMonitorExitCall = New BoundCall(syntaxNode, exitMethod, Nothing, Nothing, ImmutableArray.Create(Of BoundExpression)(boundLockObject), Nothing, exitMethod.ReturnType, suppressObjectClone:=True) Else boundMonitorExitCall = New BoundBadExpression(syntaxNode, LookupResultKind.NotReferencable, ImmutableArray(Of Symbol).Empty, ImmutableArray.Create(boundLockObject), ErrorTypeSymbol.UnknownResultType, hasErrors:=True) End If Dim boundMonitorExitCallStatement = boundMonitorExitCall.ToStatement boundMonitorExitCallStatement.SetWasCompilerGenerated() ' used to not create sequence points If boundLockTakenLocal IsNot Nothing Then Debug.Assert(boundLockTakenLocal.Type.IsBooleanType()) ' if the "new" enter method is used we need to check the temporary boolean to see if the lock was really taken. ' (maybe there was an exception after try and before the enter call). Dim boundCondition = New BoundBinaryOperator(syntaxNode, BinaryOperatorKind.Equals, boundLockTakenLocal, New BoundLiteral(syntaxNode, ConstantValue.True, boundLockTakenLocal.Type), False, boundLockTakenLocal.Type) statementInFinally = RewriteIfStatement(syntaxNode, boundCondition, boundMonitorExitCallStatement, Nothing, instrumentationTargetOpt:=Nothing) Else statementInFinally = boundMonitorExitCallStatement End If Return statementInFinally End Function End Class End Namespace
-1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/Features/Core/Portable/MetadataAsSource/AbstractMetadataAsSourceService.AbstractWrappedNamespaceOrTypeSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.DocumentationComments; namespace Microsoft.CodeAnalysis.MetadataAsSource { internal partial class AbstractMetadataAsSourceService { private abstract class AbstractWrappedNamespaceOrTypeSymbol : AbstractWrappedSymbol, INamespaceOrTypeSymbol { private readonly INamespaceOrTypeSymbol _symbol; protected AbstractWrappedNamespaceOrTypeSymbol(INamespaceOrTypeSymbol symbol, bool canImplementImplicitly, IDocumentationCommentFormattingService docCommentFormattingService) : base(symbol, canImplementImplicitly, docCommentFormattingService) { _symbol = symbol; } public abstract ImmutableArray<ISymbol> GetMembers(); public abstract ImmutableArray<ISymbol> GetMembers(string name); public abstract ImmutableArray<INamedTypeSymbol> GetTypeMembers(); public abstract ImmutableArray<INamedTypeSymbol> GetTypeMembers(string name); public abstract ImmutableArray<INamedTypeSymbol> GetTypeMembers(string name, int arity); public bool IsNamespace => _symbol.IsNamespace; public bool IsType => _symbol.IsType; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.DocumentationComments; namespace Microsoft.CodeAnalysis.MetadataAsSource { internal partial class AbstractMetadataAsSourceService { private abstract class AbstractWrappedNamespaceOrTypeSymbol : AbstractWrappedSymbol, INamespaceOrTypeSymbol { private readonly INamespaceOrTypeSymbol _symbol; protected AbstractWrappedNamespaceOrTypeSymbol(INamespaceOrTypeSymbol symbol, bool canImplementImplicitly, IDocumentationCommentFormattingService docCommentFormattingService) : base(symbol, canImplementImplicitly, docCommentFormattingService) { _symbol = symbol; } public abstract ImmutableArray<ISymbol> GetMembers(); public abstract ImmutableArray<ISymbol> GetMembers(string name); public abstract ImmutableArray<INamedTypeSymbol> GetTypeMembers(); public abstract ImmutableArray<INamedTypeSymbol> GetTypeMembers(string name); public abstract ImmutableArray<INamedTypeSymbol> GetTypeMembers(string name, int arity); public bool IsNamespace => _symbol.IsNamespace; public bool IsType => _symbol.IsType; } } }
-1
dotnet/roslyn
55,424
Fix matchnamespacetofolder analyzer/codefix
Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
ryzngard
2021-08-05T00:29:53Z
2021-08-05T06:48:11Z
cbd0fb83e317c7b2c33343b8d8d92b9cf2303db8
11776736ea4447733d3b11850c211d998c39b01d
Fix matchnamespacetofolder analyzer/codefix. Fix issues where the namespace for documents at the root would be incorrect. Fixes: #54757
./src/Compilers/Core/MSBuildTask/ICompilerOptionsHostObject.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.InteropServices; namespace Microsoft.CodeAnalysis.BuildTasks { [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("117CC9AD-299A-4898-AAFD-8ADE0FE0A1EF")] public interface ICompilerOptionsHostObject { bool SetCompilerOptions([MarshalAs(UnmanagedType.BStr)] string compilerOptions); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.InteropServices; namespace Microsoft.CodeAnalysis.BuildTasks { [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("117CC9AD-299A-4898-AAFD-8ADE0FE0A1EF")] public interface ICompilerOptionsHostObject { bool SetCompilerOptions([MarshalAs(UnmanagedType.BStr)] string compilerOptions); } }
-1
dotnet/roslyn
55,419
Make vsix's compatible with vs 2022
Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
dibarbet
2021-08-04T23:36:41Z
2021-08-06T17:54:08Z
082df2aaf6a73277fc27f9d7a5a8d18ee45d7f8b
e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028
Make vsix's compatible with vs 2022. Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
./src/Compilers/Extension/source.extension.vsixmanifest
<?xml version="1.0" encoding="utf-8"?> <PackageManifest Version="2.0.0" xmlns="http://schemas.microsoft.com/developer/vsx-schema/2011" xmlns:d="http://schemas.microsoft.com/developer/vsx-schema-design/2011"> <Metadata> <Identity Id="7922692f-f018-45e7-8f3f-d3b7c0262841" Version="|%CurrentProject%;GetVsixVersion|" Language="en-US" Publisher="Microsoft" /> <DisplayName>Roslyn Compilers</DisplayName> <Description xml:space="preserve">Package of the Roslyn compilers that enables them for Visual Studio builds.</Description> <License>EULA.rtf</License> </Metadata> <Installation Experimental="true"> <InstallationTarget Version="[15.0,]" Id="Microsoft.VisualStudio.Pro" /> </Installation> <Dependencies> <Dependency Id="Microsoft.Framework.NDP" DisplayName="Microsoft .NET Framework" d:Source="Manual" Version="[4.7.2,)" /> </Dependencies> <Assets> <Asset Type="Microsoft.VisualStudio.MefComponent" Path="|%CurrentProject%|" d:Source="Project" d:ProjectName="%CurrentProject%" /> <Asset Type="Microsoft.VisualStudio.VsPackage" Path="|%CurrentProject%;PkgdefProjectOutputGroup|" d:Source="Project" d:ProjectName="%CurrentProject%" /> </Assets> <Prerequisites> <Prerequisite Id="Microsoft.VisualStudio.Component.CoreEditor" Version="[15.0,18.0)" DisplayName="Visual Studio core editor" /> </Prerequisites> </PackageManifest>
<?xml version="1.0" encoding="utf-8"?> <PackageManifest Version="2.0.0" xmlns="http://schemas.microsoft.com/developer/vsx-schema/2011" xmlns:d="http://schemas.microsoft.com/developer/vsx-schema-design/2011"> <Metadata> <Identity Id="7922692f-f018-45e7-8f3f-d3b7c0262841" Version="|%CurrentProject%;GetVsixVersion|" Language="en-US" Publisher="Microsoft" /> <DisplayName>Roslyn Compilers</DisplayName> <Description xml:space="preserve">Package of the Roslyn compilers that enables them for Visual Studio builds.</Description> <License>EULA.rtf</License> </Metadata> <Installation Experimental="true"> <InstallationTarget Id="Microsoft.VisualStudio.Pro" Version="[17.0,]"> <ProductArchitecture>amd64</ProductArchitecture> </InstallationTarget> </Installation> <Dependencies> <Dependency Id="Microsoft.Framework.NDP" DisplayName="Microsoft .NET Framework" d:Source="Manual" Version="[4.7.2,)" /> </Dependencies> <Assets> <Asset Type="Microsoft.VisualStudio.MefComponent" Path="|%CurrentProject%|" d:Source="Project" d:ProjectName="%CurrentProject%" /> <Asset Type="Microsoft.VisualStudio.VsPackage" Path="|%CurrentProject%;PkgdefProjectOutputGroup|" d:Source="Project" d:ProjectName="%CurrentProject%" /> </Assets> <Prerequisites> <Prerequisite Id="Microsoft.VisualStudio.Component.CoreEditor" Version="[17.0,18.0)" DisplayName="Visual Studio core editor" /> </Prerequisites> </PackageManifest>
1
dotnet/roslyn
55,419
Make vsix's compatible with vs 2022
Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
dibarbet
2021-08-04T23:36:41Z
2021-08-06T17:54:08Z
082df2aaf6a73277fc27f9d7a5a8d18ee45d7f8b
e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028
Make vsix's compatible with vs 2022. Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
./src/Deployment/source.extension.vsixmanifest
<?xml version="1.0" encoding="utf-8"?> <PackageManifest Version="2.0.0" xmlns="http://schemas.microsoft.com/developer/vsx-schema/2011" xmlns:d="http://schemas.microsoft.com/developer/vsx-schema-design/2011"> <Metadata> <Identity Id="f6d4ae9d-5ca3-4e0b-9035-9457cccf53fa" Version="|%CurrentProject%;GetVsixVersion|" Language="en-US" Publisher="Microsoft" /> <DisplayName>Roslyn Insiders (Without Tool Window)</DisplayName> <Description>Pre-release build of Roslyn compilers and language services.</Description> <License>EULA.rtf</License> <AllowClientRole>true</AllowClientRole> </Metadata> <Installation> <InstallationTarget Id="Microsoft.VisualStudio.Pro" Version="[15.0,]" /> </Installation> <Dependencies> <Dependency d:ProjectName="CompilerExtension" DisplayName="Roslyn Compilers" Version="[|%CurrentProject%;GetVsixVersion|,)" d:Source="Project" d:InstallSource="Embed" d:VsixSubPath="Vsixes" Location="|CompilerExtension;VSIXContainerProjectOutputGroup|" Id="7922692f-f018-45e7-8f3f-d3b7c0262841" /> <Dependency d:ProjectName="VisualStudioSetup" DisplayName="Roslyn Language Services" Version="[|%CurrentProject%;GetVsixVersion|,)" d:Source="Project" d:InstallSource="Embed" d:VsixSubPath="Vsixes" Location="|VisualStudioSetup;VSIXContainerProjectOutputGroup|" Id="0b5e8ddb-f12d-4131-a71d-77acc26a798f" /> <Dependency d:ProjectName="ExpressionEvaluatorPackage" DisplayName="Roslyn Expression Evaluators" Version="[|%CurrentProject%;GetVsixVersion|,)" d:Source="Project" d:InstallSource="Embed" d:VsixSubPath="Vsixes" Location="|ExpressionEvaluatorPackage;VSIXContainerProjectOutputGroup|" Id="21BAC26D-2935-4D0D-A282-AD647E2592B5" /> </Dependencies> <Prerequisites> <Prerequisite Id="Microsoft.VisualStudio.Component.CoreEditor" Version="[15.0,18.0)" DisplayName="Visual Studio core editor" /> </Prerequisites> </PackageManifest>
<?xml version="1.0" encoding="utf-8"?> <PackageManifest Version="2.0.0" xmlns="http://schemas.microsoft.com/developer/vsx-schema/2011" xmlns:d="http://schemas.microsoft.com/developer/vsx-schema-design/2011"> <Metadata> <Identity Id="f6d4ae9d-5ca3-4e0b-9035-9457cccf53fa" Version="|%CurrentProject%;GetVsixVersion|" Language="en-US" Publisher="Microsoft" /> <DisplayName>Roslyn Insiders (Without Tool Window)</DisplayName> <Description>Pre-release build of Roslyn compilers and language services.</Description> <License>EULA.rtf</License> <AllowClientRole>true</AllowClientRole> </Metadata> <Installation> <InstallationTarget Id="Microsoft.VisualStudio.Pro" Version="[17.0,]"> <ProductArchitecture>amd64</ProductArchitecture> </InstallationTarget> </Installation> <Dependencies> <Dependency d:ProjectName="CompilerExtension" DisplayName="Roslyn Compilers" Version="[|%CurrentProject%;GetVsixVersion|,)" d:Source="Project" d:InstallSource="Embed" d:VsixSubPath="Vsixes" Location="|CompilerExtension;VSIXContainerProjectOutputGroup|" Id="7922692f-f018-45e7-8f3f-d3b7c0262841" /> <Dependency d:ProjectName="VisualStudioSetup" DisplayName="Roslyn Language Services" Version="[|%CurrentProject%;GetVsixVersion|,)" d:Source="Project" d:InstallSource="Embed" d:VsixSubPath="Vsixes" Location="|VisualStudioSetup;VSIXContainerProjectOutputGroup|" Id="0b5e8ddb-f12d-4131-a71d-77acc26a798f" /> <Dependency d:ProjectName="ExpressionEvaluatorPackage" DisplayName="Roslyn Expression Evaluators" Version="[|%CurrentProject%;GetVsixVersion|,)" d:Source="Project" d:InstallSource="Embed" d:VsixSubPath="Vsixes" Location="|ExpressionEvaluatorPackage;VSIXContainerProjectOutputGroup|" Id="21BAC26D-2935-4D0D-A282-AD647E2592B5" /> </Dependencies> <Prerequisites> <Prerequisite Id="Microsoft.VisualStudio.Component.CoreEditor" Version="[17.0,18.0)" DisplayName="Visual Studio core editor" /> </Prerequisites> </PackageManifest>
1
dotnet/roslyn
55,419
Make vsix's compatible with vs 2022
Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
dibarbet
2021-08-04T23:36:41Z
2021-08-06T17:54:08Z
082df2aaf6a73277fc27f9d7a5a8d18ee45d7f8b
e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028
Make vsix's compatible with vs 2022. Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
./src/ExpressionEvaluator/Package/source.extension.vsixmanifest
<?xml version="1.0" encoding="utf-8"?> <PackageManifest Version="2.0.0" xmlns="http://schemas.microsoft.com/developer/vsx-schema/2011" xmlns:d="http://schemas.microsoft.com/developer/vsx-schema-design/2011"> <Metadata> <Identity Id="21BAC26D-2935-4D0D-A282-AD647E2592B5" Version="|%CurrentProject%;GetVsixVersion|" Language="en-US" Publisher="Microsoft" /> <DisplayName>Roslyn Expression Evaluators</DisplayName> <Description xml:space="preserve">Roslyn Expression Evaluators</Description> <PackageId>Microsoft.CodeAnalysis.ExpressionEvaluator</PackageId> <License>EULA.rtf</License> <AllowClientRole>true</AllowClientRole> </Metadata> <Installation Experimental="true"> <InstallationTarget Id="Microsoft.VisualStudio.Pro" Version="[15.0,]" /> <InstallationTarget Version="[15.0,]" Id="Microsoft.VisualStudio.VSWinDesktopExpress" /> <InstallationTarget Version="[15.0,]" Id="Microsoft.VisualStudio.VWDExpress" /> <InstallationTarget Version="[15.0,]" Id="Microsoft.VisualStudio.VSWinExpress" /> </Installation> <Dependencies> <Dependency Version="[|VisualStudioSetup;GetVsixVersion|,]" DisplayName="Roslyn Language Services" Id="0b5e8ddb-f12d-4131-a71d-77acc26a798f" /> </Dependencies> <Assets> <Asset Type="DebuggerEngineExtension" d:Source="Project" d:ProjectName="BasicExpressionCompiler" Path="|BasicExpressionCompiler;VsdConfigOutputGroup|" /> <Asset Type="DebuggerEngineExtension" d:Source="Project" d:ProjectName="BasicResultProvider.Portable" Path="|BasicResultProvider.Portable;VsdConfigOutputGroup|" /> <Asset Type="DebuggerEngineExtension" d:Source="Project" d:ProjectName="CSharpExpressionCompiler" Path="|CSharpExpressionCompiler;VsdConfigOutputGroup|" /> <Asset Type="DebuggerEngineExtension" d:Source="Project" d:ProjectName="CSharpResultProvider.Portable" Path="|CSharpResultProvider.Portable;VsdConfigOutputGroup|" /> <Asset Type="DebuggerEngineExtension" d:Source="Project" d:ProjectName="FunctionResolver" Path="|FunctionResolver;VsdConfigOutputGroup|" /> <Asset Type="Microsoft.VisualStudio.VsPackage" d:Source="Project" d:ProjectName="%CurrentProject%" Path="|%CurrentProject%;PkgdefProjectOutputGroup|" /> </Assets> <Prerequisites> <Prerequisite Id="Microsoft.VisualStudio.Component.CoreEditor" Version="[15.0,18.0)" DisplayName="Visual Studio core editor" /> </Prerequisites> </PackageManifest>
<?xml version="1.0" encoding="utf-8"?> <PackageManifest Version="2.0.0" xmlns="http://schemas.microsoft.com/developer/vsx-schema/2011" xmlns:d="http://schemas.microsoft.com/developer/vsx-schema-design/2011"> <Metadata> <Identity Id="21BAC26D-2935-4D0D-A282-AD647E2592B5" Version="|%CurrentProject%;GetVsixVersion|" Language="en-US" Publisher="Microsoft" /> <DisplayName>Roslyn Expression Evaluators</DisplayName> <Description xml:space="preserve">Roslyn Expression Evaluators</Description> <PackageId>Microsoft.CodeAnalysis.ExpressionEvaluator</PackageId> <License>EULA.rtf</License> <AllowClientRole>true</AllowClientRole> </Metadata> <Installation Experimental="true"> <InstallationTarget Id="Microsoft.VisualStudio.Pro" Version="[17.0,]"> <ProductArchitecture>amd64</ProductArchitecture> </InstallationTarget> <InstallationTarget Id="Microsoft.VisualStudio.VSWinDesktopExpress" Version="[17.0,]"> <ProductArchitecture>amd64</ProductArchitecture> </InstallationTarget> <InstallationTarget Id="Microsoft.VisualStudio.VWDExpress" Version="[17.0,]"> <ProductArchitecture>amd64</ProductArchitecture> </InstallationTarget> <InstallationTarget Id="Microsoft.VisualStudio.VSWinExpress" Version="[17.0,]"> <ProductArchitecture>amd64</ProductArchitecture> </InstallationTarget> </Installation> <Dependencies> <Dependency Version="[|VisualStudioSetup;GetVsixVersion|,]" DisplayName="Roslyn Language Services" Id="0b5e8ddb-f12d-4131-a71d-77acc26a798f" /> </Dependencies> <Assets> <Asset Type="DebuggerEngineExtension" d:Source="Project" d:ProjectName="BasicExpressionCompiler" Path="|BasicExpressionCompiler;VsdConfigOutputGroup|" /> <Asset Type="DebuggerEngineExtension" d:Source="Project" d:ProjectName="BasicResultProvider.Portable" Path="|BasicResultProvider.Portable;VsdConfigOutputGroup|" /> <Asset Type="DebuggerEngineExtension" d:Source="Project" d:ProjectName="CSharpExpressionCompiler" Path="|CSharpExpressionCompiler;VsdConfigOutputGroup|" /> <Asset Type="DebuggerEngineExtension" d:Source="Project" d:ProjectName="CSharpResultProvider.Portable" Path="|CSharpResultProvider.Portable;VsdConfigOutputGroup|" /> <Asset Type="DebuggerEngineExtension" d:Source="Project" d:ProjectName="FunctionResolver" Path="|FunctionResolver;VsdConfigOutputGroup|" /> <Asset Type="Microsoft.VisualStudio.VsPackage" d:Source="Project" d:ProjectName="%CurrentProject%" Path="|%CurrentProject%;PkgdefProjectOutputGroup|" /> </Assets> <Prerequisites> <Prerequisite Id="Microsoft.VisualStudio.Component.CoreEditor" Version="[17.0,18.0)" DisplayName="Visual Studio core editor" /> </Prerequisites> </PackageManifest>
1
dotnet/roslyn
55,419
Make vsix's compatible with vs 2022
Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
dibarbet
2021-08-04T23:36:41Z
2021-08-06T17:54:08Z
082df2aaf6a73277fc27f9d7a5a8d18ee45d7f8b
e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028
Make vsix's compatible with vs 2022. Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
./src/VisualStudio/Setup.Dependencies/source.extension.vsixmanifest
<?xml version="1.0" encoding="utf-8"?> <PackageManifest Version="2.0.0" xmlns="http://schemas.microsoft.com/developer/vsx-schema/2011" xmlns:d="http://schemas.microsoft.com/developer/vsx-schema-design/2011"> <Metadata> <Identity Id="7b9f8160-9d62-48cd-9674-b487b1e17c1f" Version="|%CurrentProject%;GetVsixVersion|" Language="en-US" Publisher="Microsoft" /> <DisplayName>Roslyn Dependencies</DisplayName> <Description>Roslyn dependencies for developer deployment.</Description> <PackageId>Microsoft.CodeAnalysis.VisualStudio.Setup.Dependencies</PackageId> <License>EULA.rtf</License> </Metadata> <Installation Experimental="true"> <InstallationTarget Version="[15.0,]" Id="Microsoft.VisualStudio.Pro" /> <InstallationTarget Version="[15.0,]" Id="Microsoft.VisualStudio.VSWinDesktopExpress" /> <InstallationTarget Version="[15.0,]" Id="Microsoft.VisualStudio.VWDExpress" /> <InstallationTarget Version="[15.0,]" Id="Microsoft.VisualStudio.VSWinExpress" /> </Installation> <Dependencies> <Dependency Id="Microsoft.Framework.NDP" DisplayName="Microsoft .NET Framework" d:Source="Manual" Version="[4.7.2,)" /> </Dependencies> <Assets> </Assets> <Prerequisites> <Prerequisite Id="Microsoft.VisualStudio.Component.CoreEditor" Version="[15.0,18.0)" DisplayName="Visual Studio core editor" /> </Prerequisites> </PackageManifest>
<?xml version="1.0" encoding="utf-8"?> <PackageManifest Version="2.0.0" xmlns="http://schemas.microsoft.com/developer/vsx-schema/2011" xmlns:d="http://schemas.microsoft.com/developer/vsx-schema-design/2011"> <Metadata> <Identity Id="7b9f8160-9d62-48cd-9674-b487b1e17c1f" Version="|%CurrentProject%;GetVsixVersion|" Language="en-US" Publisher="Microsoft" /> <DisplayName>Roslyn Dependencies</DisplayName> <Description>Roslyn dependencies for developer deployment.</Description> <PackageId>Microsoft.CodeAnalysis.VisualStudio.Setup.Dependencies</PackageId> <License>EULA.rtf</License> </Metadata> <Installation Experimental="true"> <InstallationTarget Id="Microsoft.VisualStudio.Pro" Version="[17.0,]"> <ProductArchitecture>amd64</ProductArchitecture> </InstallationTarget> <InstallationTarget Id="Microsoft.VisualStudio.VSWinDesktopExpress" Version="[17.0,]"> <ProductArchitecture>amd64</ProductArchitecture> </InstallationTarget> <InstallationTarget Id="Microsoft.VisualStudio.VWDExpress" Version="[17.0,]"> <ProductArchitecture>amd64</ProductArchitecture> </InstallationTarget> <InstallationTarget Id="Microsoft.VisualStudio.VSWinExpress" Version="[17.0,]"> <ProductArchitecture>amd64</ProductArchitecture> </InstallationTarget> </Installation> <Dependencies> <Dependency Id="Microsoft.Framework.NDP" DisplayName="Microsoft .NET Framework" d:Source="Manual" Version="[4.7.2,)" /> </Dependencies> <Assets> </Assets> <Prerequisites> <Prerequisite Id="Microsoft.VisualStudio.Component.CoreEditor" Version="[17.0,18.0)" DisplayName="Visual Studio core editor" /> </Prerequisites> </PackageManifest>
1
dotnet/roslyn
55,419
Make vsix's compatible with vs 2022
Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
dibarbet
2021-08-04T23:36:41Z
2021-08-06T17:54:08Z
082df2aaf6a73277fc27f9d7a5a8d18ee45d7f8b
e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028
Make vsix's compatible with vs 2022. Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
./src/VisualStudio/Setup/source.extension.vsixmanifest
<?xml version="1.0" encoding="utf-8"?> <PackageManifest Version="2.0.0" xmlns="http://schemas.microsoft.com/developer/vsx-schema/2011" xmlns:d="http://schemas.microsoft.com/developer/vsx-schema-design/2011"> <Metadata> <Identity Id="0b5e8ddb-f12d-4131-a71d-77acc26a798f" Version="|%CurrentProject%;GetVsixVersion|" Language="en-US" Publisher="Microsoft" /> <DisplayName>Roslyn Language Services</DisplayName> <Description>C# and VB.NET language services for Visual Studio.</Description> <PackageId>Microsoft.CodeAnalysis.VisualStudio.Setup</PackageId> <License>EULA.rtf</License> <AllowClientRole>true</AllowClientRole> </Metadata> <Installation Experimental="true"> <InstallationTarget Version="[15.0,]" Id="Microsoft.VisualStudio.Pro" /> <InstallationTarget Version="[15.0,]" Id="Microsoft.VisualStudio.VSWinDesktopExpress" /> <InstallationTarget Version="[15.0,]" Id="Microsoft.VisualStudio.VWDExpress" /> <InstallationTarget Version="[15.0,]" Id="Microsoft.VisualStudio.VSWinExpress" /> </Installation> <Dependencies> <Dependency Id="Microsoft.Framework.NDP" DisplayName="Microsoft .NET Framework" d:Source="Manual" Version="[4.7.2,)" /> </Dependencies> <Assets> <Asset Type="Microsoft.VisualStudio.MefComponent" Path="Microsoft.CodeAnalysis.Workspaces.dll" /> <Asset Type="Microsoft.VisualStudio.MefComponent" Path="Microsoft.CodeAnalysis.Remote.Workspaces.dll" /> <Asset Type="Microsoft.VisualStudio.MefComponent" Path="Microsoft.CodeAnalysis.EditorFeatures.dll" /> <Asset Type="Microsoft.VisualStudio.MefComponent" Path="Microsoft.CodeAnalysis.Features.dll" /> <Asset Type="Microsoft.VisualStudio.MefComponent" Path="Microsoft.CodeAnalysis.CSharp.Features.dll" /> <Asset Type="Microsoft.VisualStudio.MefComponent" Path="Microsoft.CodeAnalysis.CSharp.Workspaces.dll" /> <Asset Type="Microsoft.VisualStudio.MefComponent" Path="Microsoft.CodeAnalysis.CSharp.EditorFeatures.dll" /> <Asset Type="Microsoft.VisualStudio.MefComponent" Path="Microsoft.CodeAnalysis.VisualBasic.Features.dll" /> <Asset Type="Microsoft.VisualStudio.MefComponent" Path="Microsoft.CodeAnalysis.VisualBasic.Workspaces.dll" /> <Asset Type="Microsoft.VisualStudio.MefComponent" Path="Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.dll" /> <Asset Type="Microsoft.VisualStudio.MefComponent" d:Source="Project" d:ProjectName="EditorFeatures.Wpf" Path="|EditorFeatures.Wpf|" /> <Asset Type="Microsoft.VisualStudio.MefComponent" Path="Microsoft.CodeAnalysis.EditorFeatures.Text.dll" /> <Asset Type="Microsoft.VisualStudio.MefComponent" Path="Microsoft.VisualStudio.LanguageServices.dll" /> <Asset Type="Microsoft.VisualStudio.MefComponent" d:Source="Project" d:ProjectName="XamlVisualStudio" Path="|XamlVisualStudio|" /> <Asset Type="Microsoft.VisualStudio.MefComponent" d:Source="Project" d:ProjectName="BasicVisualStudio" Path="|BasicVisualStudio|" /> <Asset Type="Microsoft.VisualStudio.MefComponent" d:Source="Project" d:ProjectName="CSharpVisualStudio" Path="|CSharpVisualStudio|" /> <Asset Type="Microsoft.VisualStudio.MefComponent" d:Source="Project" d:ProjectName="ServicesVisualStudioImpl" Path="|ServicesVisualStudioImpl|" /> <Asset Type="Microsoft.VisualStudio.VsPackage" d:Source="Project" d:ProjectName="ServicesVisualStudio" Path="|ServicesVisualStudio;PkgdefProjectOutputGroup|" /> <Asset Type="Microsoft.VisualStudio.VsPackage" d:Source="Project" d:ProjectName="BasicVisualStudio" Path="|BasicVisualStudio;PkgdefProjectOutputGroup|" /> <Asset Type="Microsoft.VisualStudio.VsPackage" d:Source="Project" d:ProjectName="CSharpVisualStudio" Path="|CSharpVisualStudio;PkgdefProjectOutputGroup|" /> <Asset Type="Microsoft.VisualStudio.VsPackage" d:Source="Project" d:ProjectName="%CurrentProject%" Path="|%CurrentProject%;PkgdefProjectOutputGroup|" /> <Asset Type="DebuggerEngineExtension" d:Source="Project" d:ProjectName="ServicesVisualStudio" Path="|ServicesVisualStudio;VsdConfigOutputGroup|" /> <Asset Type="Microsoft.VisualStudio.Analyzer" Path="Microsoft.CodeAnalysis.CSharp.dll" /> <Asset Type="Microsoft.VisualStudio.Analyzer" Path="Microsoft.CodeAnalysis.VisualBasic.dll" /> <Asset Type="Microsoft.VisualStudio.Analyzer" Path="Microsoft.CodeAnalysis.EditorFeatures.dll" /> <Asset Type="Microsoft.VisualStudio.Analyzer" Path="Microsoft.CodeAnalysis.Features.dll" /> <Asset Type="Microsoft.VisualStudio.Analyzer" Path="Microsoft.CodeAnalysis.CSharp.Features.dll" /> <Asset Type="Microsoft.VisualStudio.Analyzer" Path="Microsoft.CodeAnalysis.CSharp.EditorFeatures.dll" /> <Asset Type="Microsoft.VisualStudio.Analyzer" Path="Microsoft.CodeAnalysis.VisualBasic.Features.dll" /> <Asset Type="Microsoft.VisualStudio.Analyzer" Path="Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.dll" /> <Asset Type="Microsoft.VisualStudio.Analyzer" d:Source="Project" d:ProjectName="XamlVisualStudio" Path="|XamlVisualStudio|" /> <Asset Type="Microsoft.VisualStudio.CodeLensComponent" d:Source="File" Path="Microsoft.VisualStudio.LanguageServices.CodeLens.dll" /> <Asset Type="Microsoft.VisualStudio.MefComponent" Path="Microsoft.CodeAnalysis.ExternalAccess.Apex.dll" /> <Asset Type="Microsoft.VisualStudio.MefComponent" Path="Microsoft.CodeAnalysis.ExternalAccess.Debugger.dll" /> <Asset Type="Microsoft.VisualStudio.MefComponent" Path="Microsoft.CodeAnalysis.ExternalAccess.FSharp.dll" /> <Asset Type="Microsoft.VisualStudio.MefComponent" Path="Microsoft.CodeAnalysis.ExternalAccess.Razor.dll" /> <Asset Type="Microsoft.VisualStudio.MefComponent" Path="Microsoft.CodeAnalysis.LanguageServer.Protocol.dll" /> <Asset Type="Microsoft.VisualStudio.Analyzer" Path="Microsoft.CodeAnalysis.ExternalAccess.FSharp.dll" /> <Asset Type="Microsoft.VisualStudio.MefComponent" Path="Microsoft.VisualStudio.LanguageServices.LiveShare.dll" /> <Asset Type="Microsoft.VisualStudio.MefComponent" Path="Microsoft.CodeAnalysis.LanguageServer.Protocol.dll" /> <!-- ServiceHub assets are added by msbuild target --> <!--#SERVICEHUB_ASSETS#--> </Assets> <Prerequisites> <Prerequisite Id="Microsoft.VisualStudio.Component.CoreEditor" Version="[15.0,18.0)" DisplayName="Visual Studio core editor" /> <Prerequisite Id="Microsoft.DiaSymReader.Native" Version="[15.0,18.0)" DisplayName="Windows PDB reader/writer" /> <Prerequisite Id="Microsoft.VisualStudio.InteractiveWindow" Version="[3.0.0.0,4.0.0.0)" DisplayName="Interactive Window" /> </Prerequisites> </PackageManifest>
<?xml version="1.0" encoding="utf-8"?> <PackageManifest Version="2.0.0" xmlns="http://schemas.microsoft.com/developer/vsx-schema/2011" xmlns:d="http://schemas.microsoft.com/developer/vsx-schema-design/2011"> <Metadata> <Identity Id="0b5e8ddb-f12d-4131-a71d-77acc26a798f" Version="|%CurrentProject%;GetVsixVersion|" Language="en-US" Publisher="Microsoft" /> <DisplayName>Roslyn Language Services</DisplayName> <Description>C# and VB.NET language services for Visual Studio.</Description> <PackageId>Microsoft.CodeAnalysis.VisualStudio.Setup</PackageId> <License>EULA.rtf</License> <AllowClientRole>true</AllowClientRole> </Metadata> <Installation Experimental="true"> <InstallationTarget Id="Microsoft.VisualStudio.Pro" Version="[17.0,]"> <ProductArchitecture>amd64</ProductArchitecture> </InstallationTarget> <InstallationTarget Id="Microsoft.VisualStudio.VSWinDesktopExpress" Version="[17.0,]"> <ProductArchitecture>amd64</ProductArchitecture> </InstallationTarget> <InstallationTarget Id="Microsoft.VisualStudio.VWDExpress" Version="[17.0,]"> <ProductArchitecture>amd64</ProductArchitecture> </InstallationTarget> <InstallationTarget Id="Microsoft.VisualStudio.VSWinExpress" Version="[17.0,]"> <ProductArchitecture>amd64</ProductArchitecture> </InstallationTarget> </Installation> <Dependencies> <Dependency Id="Microsoft.Framework.NDP" DisplayName="Microsoft .NET Framework" d:Source="Manual" Version="[4.7.2,)" /> </Dependencies> <Assets> <Asset Type="Microsoft.VisualStudio.MefComponent" Path="Microsoft.CodeAnalysis.Workspaces.dll" /> <Asset Type="Microsoft.VisualStudio.MefComponent" Path="Microsoft.CodeAnalysis.Remote.Workspaces.dll" /> <Asset Type="Microsoft.VisualStudio.MefComponent" Path="Microsoft.CodeAnalysis.EditorFeatures.dll" /> <Asset Type="Microsoft.VisualStudio.MefComponent" Path="Microsoft.CodeAnalysis.Features.dll" /> <Asset Type="Microsoft.VisualStudio.MefComponent" Path="Microsoft.CodeAnalysis.CSharp.Features.dll" /> <Asset Type="Microsoft.VisualStudio.MefComponent" Path="Microsoft.CodeAnalysis.CSharp.Workspaces.dll" /> <Asset Type="Microsoft.VisualStudio.MefComponent" Path="Microsoft.CodeAnalysis.CSharp.EditorFeatures.dll" /> <Asset Type="Microsoft.VisualStudio.MefComponent" Path="Microsoft.CodeAnalysis.VisualBasic.Features.dll" /> <Asset Type="Microsoft.VisualStudio.MefComponent" Path="Microsoft.CodeAnalysis.VisualBasic.Workspaces.dll" /> <Asset Type="Microsoft.VisualStudio.MefComponent" Path="Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.dll" /> <Asset Type="Microsoft.VisualStudio.MefComponent" d:Source="Project" d:ProjectName="EditorFeatures.Wpf" Path="|EditorFeatures.Wpf|" /> <Asset Type="Microsoft.VisualStudio.MefComponent" Path="Microsoft.CodeAnalysis.EditorFeatures.Text.dll" /> <Asset Type="Microsoft.VisualStudio.MefComponent" Path="Microsoft.VisualStudio.LanguageServices.dll" /> <Asset Type="Microsoft.VisualStudio.MefComponent" d:Source="Project" d:ProjectName="XamlVisualStudio" Path="|XamlVisualStudio|" /> <Asset Type="Microsoft.VisualStudio.MefComponent" d:Source="Project" d:ProjectName="BasicVisualStudio" Path="|BasicVisualStudio|" /> <Asset Type="Microsoft.VisualStudio.MefComponent" d:Source="Project" d:ProjectName="CSharpVisualStudio" Path="|CSharpVisualStudio|" /> <Asset Type="Microsoft.VisualStudio.MefComponent" d:Source="Project" d:ProjectName="ServicesVisualStudioImpl" Path="|ServicesVisualStudioImpl|" /> <Asset Type="Microsoft.VisualStudio.VsPackage" d:Source="Project" d:ProjectName="ServicesVisualStudio" Path="|ServicesVisualStudio;PkgdefProjectOutputGroup|" /> <Asset Type="Microsoft.VisualStudio.VsPackage" d:Source="Project" d:ProjectName="BasicVisualStudio" Path="|BasicVisualStudio;PkgdefProjectOutputGroup|" /> <Asset Type="Microsoft.VisualStudio.VsPackage" d:Source="Project" d:ProjectName="CSharpVisualStudio" Path="|CSharpVisualStudio;PkgdefProjectOutputGroup|" /> <Asset Type="Microsoft.VisualStudio.VsPackage" d:Source="Project" d:ProjectName="%CurrentProject%" Path="|%CurrentProject%;PkgdefProjectOutputGroup|" /> <Asset Type="DebuggerEngineExtension" d:Source="Project" d:ProjectName="ServicesVisualStudio" Path="|ServicesVisualStudio;VsdConfigOutputGroup|" /> <Asset Type="Microsoft.VisualStudio.Analyzer" Path="Microsoft.CodeAnalysis.CSharp.dll" /> <Asset Type="Microsoft.VisualStudio.Analyzer" Path="Microsoft.CodeAnalysis.VisualBasic.dll" /> <Asset Type="Microsoft.VisualStudio.Analyzer" Path="Microsoft.CodeAnalysis.EditorFeatures.dll" /> <Asset Type="Microsoft.VisualStudio.Analyzer" Path="Microsoft.CodeAnalysis.Features.dll" /> <Asset Type="Microsoft.VisualStudio.Analyzer" Path="Microsoft.CodeAnalysis.CSharp.Features.dll" /> <Asset Type="Microsoft.VisualStudio.Analyzer" Path="Microsoft.CodeAnalysis.CSharp.EditorFeatures.dll" /> <Asset Type="Microsoft.VisualStudio.Analyzer" Path="Microsoft.CodeAnalysis.VisualBasic.Features.dll" /> <Asset Type="Microsoft.VisualStudio.Analyzer" Path="Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.dll" /> <Asset Type="Microsoft.VisualStudio.Analyzer" d:Source="Project" d:ProjectName="XamlVisualStudio" Path="|XamlVisualStudio|" /> <Asset Type="Microsoft.VisualStudio.CodeLensComponent" d:Source="File" Path="Microsoft.VisualStudio.LanguageServices.CodeLens.dll" /> <Asset Type="Microsoft.VisualStudio.MefComponent" Path="Microsoft.CodeAnalysis.ExternalAccess.Apex.dll" /> <Asset Type="Microsoft.VisualStudio.MefComponent" Path="Microsoft.CodeAnalysis.ExternalAccess.Debugger.dll" /> <Asset Type="Microsoft.VisualStudio.MefComponent" Path="Microsoft.CodeAnalysis.ExternalAccess.FSharp.dll" /> <Asset Type="Microsoft.VisualStudio.MefComponent" Path="Microsoft.CodeAnalysis.ExternalAccess.Razor.dll" /> <Asset Type="Microsoft.VisualStudio.MefComponent" Path="Microsoft.CodeAnalysis.LanguageServer.Protocol.dll" /> <Asset Type="Microsoft.VisualStudio.Analyzer" Path="Microsoft.CodeAnalysis.ExternalAccess.FSharp.dll" /> <Asset Type="Microsoft.VisualStudio.MefComponent" Path="Microsoft.VisualStudio.LanguageServices.LiveShare.dll" /> <Asset Type="Microsoft.VisualStudio.MefComponent" Path="Microsoft.CodeAnalysis.LanguageServer.Protocol.dll" /> <!-- ServiceHub assets are added by msbuild target --> <!--#SERVICEHUB_ASSETS#--> </Assets> <Prerequisites> <Prerequisite Id="Microsoft.VisualStudio.Component.CoreEditor" Version="[17.0,18.0)" DisplayName="Visual Studio core editor" /> <Prerequisite Id="Microsoft.DiaSymReader.Native" Version="[17.0,18.0)" DisplayName="Windows PDB reader/writer" /> <Prerequisite Id="Microsoft.VisualStudio.InteractiveWindow" Version="[4.0.0.0,5.0.0.0)" DisplayName="Interactive Window" /> </Prerequisites> </PackageManifest>
1
dotnet/roslyn
55,419
Make vsix's compatible with vs 2022
Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
dibarbet
2021-08-04T23:36:41Z
2021-08-06T17:54:08Z
082df2aaf6a73277fc27f9d7a5a8d18ee45d7f8b
e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028
Make vsix's compatible with vs 2022. Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
./src/VisualStudio/VisualStudioDiagnosticsToolWindow/source.extension.vsixmanifest
<?xml version="1.0" encoding="utf-8"?> <PackageManifest Version="2.0.0" xmlns="http://schemas.microsoft.com/developer/vsx-schema/2011" xmlns:d="http://schemas.microsoft.com/developer/vsx-schema-design/2011"> <Metadata> <Identity Id="49e24138-9ee3-49e0-8ede-6b39f49303bf" Version="|%CurrentProject%;GetVsixVersion|" Language="en-US" Publisher="Microsoft" /> <DisplayName>Roslyn Diagnostics</DisplayName> <Description xml:space="preserve">Roslyn Diagnostics Window</Description> <License>EULA.rtf</License> </Metadata> <Installation Experimental="true"> <InstallationTarget Id="Microsoft.VisualStudio.Pro" Version="[15.0,]" /> </Installation> <Assets> <Asset Type="Microsoft.VisualStudio.MefComponent" d:Source="Project" d:ProjectName="%CurrentProject%" Path="|%CurrentProject%|" /> <Asset Type="Microsoft.VisualStudio.VsPackage" d:Source="Project" d:ProjectName="%CurrentProject%" Path="|%CurrentProject%;PkgdefProjectOutputGroup|" /> </Assets> <Prerequisites> <Prerequisite Id="Microsoft.VisualStudio.Component.CoreEditor" Version="[15.0,18.0)" DisplayName="Visual Studio core editor" /> </Prerequisites> </PackageManifest>
<?xml version="1.0" encoding="utf-8"?> <PackageManifest Version="2.0.0" xmlns="http://schemas.microsoft.com/developer/vsx-schema/2011" xmlns:d="http://schemas.microsoft.com/developer/vsx-schema-design/2011"> <Metadata> <Identity Id="49e24138-9ee3-49e0-8ede-6b39f49303bf" Version="|%CurrentProject%;GetVsixVersion|" Language="en-US" Publisher="Microsoft" /> <DisplayName>Roslyn Diagnostics</DisplayName> <Description xml:space="preserve">Roslyn Diagnostics Window</Description> <License>EULA.rtf</License> </Metadata> <Installation Experimental="true"> <InstallationTarget Id="Microsoft.VisualStudio.Pro" Version="[17.0,]"> <ProductArchitecture>amd64</ProductArchitecture> </InstallationTarget> </Installation> <Assets> <Asset Type="Microsoft.VisualStudio.MefComponent" d:Source="Project" d:ProjectName="%CurrentProject%" Path="|%CurrentProject%|" /> <Asset Type="Microsoft.VisualStudio.VsPackage" d:Source="Project" d:ProjectName="%CurrentProject%" Path="|%CurrentProject%;PkgdefProjectOutputGroup|" /> </Assets> <Prerequisites> <Prerequisite Id="Microsoft.VisualStudio.Component.CoreEditor" Version="[17.0,18.0)" DisplayName="Visual Studio core editor" /> </Prerequisites> </PackageManifest>
1
dotnet/roslyn
55,419
Make vsix's compatible with vs 2022
Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
dibarbet
2021-08-04T23:36:41Z
2021-08-06T17:54:08Z
082df2aaf6a73277fc27f9d7a5a8d18ee45d7f8b
e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028
Make vsix's compatible with vs 2022. Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
./src/VisualStudio/IntegrationTest/TestSetup/source.extension.vsixmanifest
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <PackageManifest Version="2.0.0" xmlns="http://schemas.microsoft.com/developer/vsx-schema/2011" xmlns:d="http://schemas.microsoft.com/developer/vsx-schema-design/2011"> <Metadata> <Identity Id="d0122878-51f1-4b36-95ec-dec2079a2a84" Version="|%CurrentProject%;GetVsixVersion|" Language="en-US" Publisher="Microsoft" /> <DisplayName>Visual Studio Integration Test Support</DisplayName> <Description xml:space="preserve">Support for running Visual Studio integration tests.</Description> <License>EULA.rtf</License> </Metadata> <Installation Experimental="true"> <InstallationTarget Id="Microsoft.VisualStudio.Community" Version="[17.0,]"> <ProductArchitecture>x86</ProductArchitecture> </InstallationTarget> <InstallationTarget Id="Microsoft.VisualStudio.Community" Version="[17.0,]"> <ProductArchitecture>amd64</ProductArchitecture> </InstallationTarget> </Installation> <Dependencies> <Dependency Id="0b5e8ddb-f12d-4131-a71d-77acc26a798f" DisplayName="Roslyn Language Services" d:Source="Project" Version="[|VisualStudioSetup;GetVsixVersion|,]" d:ProjectName="VisualStudioSetup" /> </Dependencies> <Assets> <Asset Type="Microsoft.VisualStudio.VsPackage" d:Source="Project" d:ProjectName="%CurrentProject%" Path="|%CurrentProject%;PkgdefProjectOutputGroup|" /> <Asset Type="Microsoft.VisualStudio.MefComponent" d:Source="Project" d:ProjectName="%CurrentProject%" Path="|%CurrentProject%|" /> <Asset Type="Microsoft.VisualStudio.MefComponent" d:Source="Project" d:ProjectName="Diagnostics" Path="|Diagnostics|" AssemblyName="|Diagnostics;AssemblyName|" /> </Assets> <Prerequisites> <Prerequisite Id="Microsoft.VisualStudio.Component.CoreEditor" Version="[17.0,18.0)" DisplayName="Visual Studio Core Editor" /> </Prerequisites> </PackageManifest>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <PackageManifest Version="2.0.0" xmlns="http://schemas.microsoft.com/developer/vsx-schema/2011" xmlns:d="http://schemas.microsoft.com/developer/vsx-schema-design/2011"> <Metadata> <Identity Id="d0122878-51f1-4b36-95ec-dec2079a2a84" Version="|%CurrentProject%;GetVsixVersion|" Language="en-US" Publisher="Microsoft" /> <DisplayName>Visual Studio Integration Test Support</DisplayName> <Description xml:space="preserve">Support for running Visual Studio integration tests.</Description> <License>EULA.rtf</License> </Metadata> <Installation Experimental="true"> <InstallationTarget Id="Microsoft.VisualStudio.Community" Version="[17.0,]"> <ProductArchitecture>x86</ProductArchitecture> </InstallationTarget> <InstallationTarget Id="Microsoft.VisualStudio.Community" Version="[17.0,]"> <ProductArchitecture>amd64</ProductArchitecture> </InstallationTarget> </Installation> <Dependencies> <Dependency Id="0b5e8ddb-f12d-4131-a71d-77acc26a798f" DisplayName="Roslyn Language Services" d:Source="Project" Version="[|VisualStudioSetup;GetVsixVersion|,]" d:ProjectName="VisualStudioSetup" /> </Dependencies> <Assets> <Asset Type="Microsoft.VisualStudio.VsPackage" d:Source="Project" d:ProjectName="%CurrentProject%" Path="|%CurrentProject%;PkgdefProjectOutputGroup|" /> <Asset Type="Microsoft.VisualStudio.MefComponent" d:Source="Project" d:ProjectName="%CurrentProject%" Path="|%CurrentProject%|" /> <Asset Type="Microsoft.VisualStudio.MefComponent" d:Source="Project" d:ProjectName="Diagnostics" Path="|Diagnostics|" AssemblyName="|Diagnostics;AssemblyName|" /> </Assets> <Prerequisites> <Prerequisite Id="Microsoft.VisualStudio.Component.CoreEditor" Version="[17.0,18.0)" DisplayName="Visual Studio Core Editor" /> </Prerequisites> </PackageManifest>
-1
dotnet/roslyn
55,419
Make vsix's compatible with vs 2022
Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
dibarbet
2021-08-04T23:36:41Z
2021-08-06T17:54:08Z
082df2aaf6a73277fc27f9d7a5a8d18ee45d7f8b
e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028
Make vsix's compatible with vs 2022. Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
./src/EditorFeatures/Core/ICommandHandlerServiceFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; namespace Microsoft.CodeAnalysis.Editor { // This is defined only to allow TypeScript to still import it and pass it to the VenusCommandHandler constructor. // The commit that is is introducing this type can be reverted once TypeScript has moved off of the use. [Obsolete("This is a compatibility shim for TypeScript; please do not use it.")] internal interface ICommandHandlerServiceFactory { } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; namespace Microsoft.CodeAnalysis.Editor { // This is defined only to allow TypeScript to still import it and pass it to the VenusCommandHandler constructor. // The commit that is is introducing this type can be reverted once TypeScript has moved off of the use. [Obsolete("This is a compatibility shim for TypeScript; please do not use it.")] internal interface ICommandHandlerServiceFactory { } }
-1
dotnet/roslyn
55,419
Make vsix's compatible with vs 2022
Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
dibarbet
2021-08-04T23:36:41Z
2021-08-06T17:54:08Z
082df2aaf6a73277fc27f9d7a5a8d18ee45d7f8b
e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028
Make vsix's compatible with vs 2022. Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/RegionKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class RegionKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public RegionKeywordRecommender() : base(SyntaxKind.RegionKeyword, isValidInPreprocessorContext: true, shouldFormatOnCommit: true) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) => context.IsPreProcessorKeywordContext; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class RegionKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public RegionKeywordRecommender() : base(SyntaxKind.RegionKeyword, isValidInPreprocessorContext: true, shouldFormatOnCommit: true) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) => context.IsPreProcessorKeywordContext; } }
-1
dotnet/roslyn
55,419
Make vsix's compatible with vs 2022
Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
dibarbet
2021-08-04T23:36:41Z
2021-08-06T17:54:08Z
082df2aaf6a73277fc27f9d7a5a8d18ee45d7f8b
e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028
Make vsix's compatible with vs 2022. Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Statements/LoopKeywordRecommender.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Statements ''' <summary> ''' Recommends the "Loop" statement. ''' </summary> Friend Class LoopKeywordRecommender Inherits AbstractKeywordRecommender Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) Dim targetToken = context.TargetToken If context.IsSingleLineStatementContext Then Dim doBlock = targetToken.GetAncestor(Of DoLoopBlockSyntax)() If doBlock Is Nothing OrElse Not doBlock.LoopStatement.IsMissing Then Return ImmutableArray(Of RecommendedKeyword).Empty End If If doBlock.Kind <> SyntaxKind.SimpleDoLoopBlock Then Return ImmutableArray.Create(New RecommendedKeyword("Loop", VBFeaturesResources.Terminates_a_loop_that_is_introduced_with_a_Do_statement)) Else Return ImmutableArray.Create( New RecommendedKeyword("Loop", VBFeaturesResources.Terminates_a_loop_that_is_introduced_with_a_Do_statement), New RecommendedKeyword("Loop Until", VBFeaturesResources.Repeats_a_block_of_statements_until_a_Boolean_condition_becomes_true_Do_Loop_Until_condition), New RecommendedKeyword("Loop While", VBFeaturesResources.Repeats_a_block_of_statements_while_a_Boolean_condition_is_true_Do_Loop_While_condition)) End If End If Return ImmutableArray(Of RecommendedKeyword).Empty End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Statements ''' <summary> ''' Recommends the "Loop" statement. ''' </summary> Friend Class LoopKeywordRecommender Inherits AbstractKeywordRecommender Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) Dim targetToken = context.TargetToken If context.IsSingleLineStatementContext Then Dim doBlock = targetToken.GetAncestor(Of DoLoopBlockSyntax)() If doBlock Is Nothing OrElse Not doBlock.LoopStatement.IsMissing Then Return ImmutableArray(Of RecommendedKeyword).Empty End If If doBlock.Kind <> SyntaxKind.SimpleDoLoopBlock Then Return ImmutableArray.Create(New RecommendedKeyword("Loop", VBFeaturesResources.Terminates_a_loop_that_is_introduced_with_a_Do_statement)) Else Return ImmutableArray.Create( New RecommendedKeyword("Loop", VBFeaturesResources.Terminates_a_loop_that_is_introduced_with_a_Do_statement), New RecommendedKeyword("Loop Until", VBFeaturesResources.Repeats_a_block_of_statements_until_a_Boolean_condition_becomes_true_Do_Loop_Until_condition), New RecommendedKeyword("Loop While", VBFeaturesResources.Repeats_a_block_of_statements_while_a_Boolean_condition_is_true_Do_Loop_While_condition)) End If End If Return ImmutableArray(Of RecommendedKeyword).Empty End Function End Class End Namespace
-1
dotnet/roslyn
55,419
Make vsix's compatible with vs 2022
Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
dibarbet
2021-08-04T23:36:41Z
2021-08-06T17:54:08Z
082df2aaf6a73277fc27f9d7a5a8d18ee45d7f8b
e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028
Make vsix's compatible with vs 2022. Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
./src/VisualStudio/TestUtilities2/CodeModel/CodeModelTestState.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.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel Imports Microsoft.VisualStudio.LanguageServices.Implementation.Interop Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel Friend Class CodeModelTestState Implements IDisposable Public ReadOnly Workspace As TestWorkspace Private ReadOnly _visualStudioWorkspace As VisualStudioWorkspace Private ReadOnly _rootCodeModel As ComHandle(Of EnvDTE.CodeModel, RootCodeModel) Private ReadOnly _fileCodeModel As ComHandle(Of EnvDTE80.FileCodeModel2, FileCodeModel) Private ReadOnly _codeModelService As ICodeModelService Public Sub New( workspace As TestWorkspace, visualStudioWorkspace As VisualStudioWorkspace, rootCodeModel As ComHandle(Of EnvDTE.CodeModel, RootCodeModel), fileCodeModel As ComHandle(Of EnvDTE80.FileCodeModel2, FileCodeModel), codeModelService As ICodeModelService ) If workspace Is Nothing Then Throw New ArgumentNullException(NameOf(workspace)) End If If codeModelService Is Nothing Then Throw New ArgumentNullException(NameOf(codeModelService)) End If Me.Workspace = workspace _visualStudioWorkspace = visualStudioWorkspace _rootCodeModel = rootCodeModel _fileCodeModel = fileCodeModel _codeModelService = codeModelService End Sub Public ReadOnly Property VisualStudioWorkspace As VisualStudioWorkspace Get Return _visualStudioWorkspace End Get End Property Public ReadOnly Property FileCodeModel As EnvDTE80.FileCodeModel2 Get Return _fileCodeModel.Handle End Get End Property Public ReadOnly Property FileCodeModelObject As FileCodeModel Get Return _fileCodeModel.Object End Get End Property Public ReadOnly Property RootCodeModel As EnvDTE.CodeModel Get Return _rootCodeModel.Handle End Get End Property Public ReadOnly Property RootCodeModelObject As RootCodeModel Get Return _rootCodeModel.Object End Get End Property Public ReadOnly Property CodeModelService As ICodeModelService Get Return _codeModelService End Get End Property #Region "IDisposable Support" Private _disposedValue As Boolean ' To detect redundant calls Protected Overridable Sub Dispose(disposing As Boolean) If Not disposing Then FailFast.Fail("TestWorkspaceAndFileModelCodel GC'd without call to Dispose()!") End If If Not Me._disposedValue Then If disposing Then VisualStudioWorkspace.Dispose() Workspace.Dispose() End If End If Me._disposedValue = True End Sub Protected Overrides Sub Finalize() Dispose(False) MyBase.Finalize() End Sub Public Sub Dispose() Implements IDisposable.Dispose Dispose(True) GC.SuppressFinalize(Me) End Sub #End Region End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel Imports Microsoft.VisualStudio.LanguageServices.Implementation.Interop Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel Friend Class CodeModelTestState Implements IDisposable Public ReadOnly Workspace As TestWorkspace Private ReadOnly _visualStudioWorkspace As VisualStudioWorkspace Private ReadOnly _rootCodeModel As ComHandle(Of EnvDTE.CodeModel, RootCodeModel) Private ReadOnly _fileCodeModel As ComHandle(Of EnvDTE80.FileCodeModel2, FileCodeModel) Private ReadOnly _codeModelService As ICodeModelService Public Sub New( workspace As TestWorkspace, visualStudioWorkspace As VisualStudioWorkspace, rootCodeModel As ComHandle(Of EnvDTE.CodeModel, RootCodeModel), fileCodeModel As ComHandle(Of EnvDTE80.FileCodeModel2, FileCodeModel), codeModelService As ICodeModelService ) If workspace Is Nothing Then Throw New ArgumentNullException(NameOf(workspace)) End If If codeModelService Is Nothing Then Throw New ArgumentNullException(NameOf(codeModelService)) End If Me.Workspace = workspace _visualStudioWorkspace = visualStudioWorkspace _rootCodeModel = rootCodeModel _fileCodeModel = fileCodeModel _codeModelService = codeModelService End Sub Public ReadOnly Property VisualStudioWorkspace As VisualStudioWorkspace Get Return _visualStudioWorkspace End Get End Property Public ReadOnly Property FileCodeModel As EnvDTE80.FileCodeModel2 Get Return _fileCodeModel.Handle End Get End Property Public ReadOnly Property FileCodeModelObject As FileCodeModel Get Return _fileCodeModel.Object End Get End Property Public ReadOnly Property RootCodeModel As EnvDTE.CodeModel Get Return _rootCodeModel.Handle End Get End Property Public ReadOnly Property RootCodeModelObject As RootCodeModel Get Return _rootCodeModel.Object End Get End Property Public ReadOnly Property CodeModelService As ICodeModelService Get Return _codeModelService End Get End Property #Region "IDisposable Support" Private _disposedValue As Boolean ' To detect redundant calls Protected Overridable Sub Dispose(disposing As Boolean) If Not disposing Then FailFast.Fail("TestWorkspaceAndFileModelCodel GC'd without call to Dispose()!") End If If Not Me._disposedValue Then If disposing Then VisualStudioWorkspace.Dispose() Workspace.Dispose() End If End If Me._disposedValue = True End Sub Protected Overrides Sub Finalize() Dispose(False) MyBase.Finalize() End Sub Public Sub Dispose() Implements IDisposable.Dispose Dispose(True) GC.SuppressFinalize(Me) End Sub #End Region End Class End Namespace
-1
dotnet/roslyn
55,419
Make vsix's compatible with vs 2022
Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
dibarbet
2021-08-04T23:36:41Z
2021-08-06T17:54:08Z
082df2aaf6a73277fc27f9d7a5a8d18ee45d7f8b
e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028
Make vsix's compatible with vs 2022. Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
./src/EditorFeatures/VisualBasicTest/Recommendations/ArrayStatements/ReDimKeywordRecommenderTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.ArrayStatements Public Class ReDimKeywordRecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ReDimInMethodBodyTest() VerifyRecommendationsContain(<MethodBody>|</MethodBody>, "ReDim") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ReDimAfterStatementTest() VerifyRecommendationsContain(<MethodBody> Dim x |</MethodBody>, "ReDim") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ReDimMissingInClassBlockTest() VerifyRecommendationsMissing(<ClassDeclaration>|</ClassDeclaration>, "ReDim") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ReDimInSingleLineLambdaTest() VerifyRecommendationsContain(<MethodBody>Dim x = Sub() |</MethodBody>, "ReDim") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ReDimNotInSingleLineFunctionLambdaTest() VerifyRecommendationsMissing(<MethodBody>Dim x = Function() |</MethodBody>, "ReDim") End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.ArrayStatements Public Class ReDimKeywordRecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ReDimInMethodBodyTest() VerifyRecommendationsContain(<MethodBody>|</MethodBody>, "ReDim") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ReDimAfterStatementTest() VerifyRecommendationsContain(<MethodBody> Dim x |</MethodBody>, "ReDim") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ReDimMissingInClassBlockTest() VerifyRecommendationsMissing(<ClassDeclaration>|</ClassDeclaration>, "ReDim") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ReDimInSingleLineLambdaTest() VerifyRecommendationsContain(<MethodBody>Dim x = Sub() |</MethodBody>, "ReDim") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ReDimNotInSingleLineFunctionLambdaTest() VerifyRecommendationsMissing(<MethodBody>Dim x = Function() |</MethodBody>, "ReDim") End Sub End Class End Namespace
-1
dotnet/roslyn
55,419
Make vsix's compatible with vs 2022
Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
dibarbet
2021-08-04T23:36:41Z
2021-08-06T17:54:08Z
082df2aaf6a73277fc27f9d7a5a8d18ee45d7f8b
e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028
Make vsix's compatible with vs 2022. Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
./src/Compilers/CSharp/Portable/Symbols/Source/SourceTypeParameterSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Base class for type and method type parameters. /// </summary> internal abstract class SourceTypeParameterSymbolBase : TypeParameterSymbol, IAttributeTargetSymbol { private readonly ImmutableArray<SyntaxReference> _syntaxRefs; private readonly ImmutableArray<Location> _locations; private readonly string _name; private readonly short _ordinal; private SymbolCompletionState _state; private CustomAttributesBag<CSharpAttributeData> _lazyCustomAttributesBag; private TypeParameterBounds _lazyBounds = TypeParameterBounds.Unset; protected SourceTypeParameterSymbolBase(string name, int ordinal, ImmutableArray<Location> locations, ImmutableArray<SyntaxReference> syntaxRefs) { Debug.Assert(!syntaxRefs.IsEmpty); _name = name; _ordinal = (short)ordinal; _locations = locations; _syntaxRefs = syntaxRefs; } public override ImmutableArray<Location> Locations { get { return _locations; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return _syntaxRefs; } } internal ImmutableArray<SyntaxReference> SyntaxReferences { get { return _syntaxRefs; } } public override int Ordinal { get { return _ordinal; } } public override VarianceKind Variance { get { return VarianceKind.None; } } public override string Name { get { return _name; } } internal override ImmutableArray<TypeWithAnnotations> GetConstraintTypes(ConsList<TypeParameterSymbol> inProgress) { var bounds = this.GetBounds(inProgress); return (bounds != null) ? bounds.ConstraintTypes : ImmutableArray<TypeWithAnnotations>.Empty; } internal override ImmutableArray<NamedTypeSymbol> GetInterfaces(ConsList<TypeParameterSymbol> inProgress) { var bounds = this.GetBounds(inProgress); return (bounds != null) ? bounds.Interfaces : ImmutableArray<NamedTypeSymbol>.Empty; } internal override NamedTypeSymbol GetEffectiveBaseClass(ConsList<TypeParameterSymbol> inProgress) { var bounds = this.GetBounds(inProgress); return (bounds != null) ? bounds.EffectiveBaseClass : this.GetDefaultBaseType(); } internal override TypeSymbol GetDeducedBaseType(ConsList<TypeParameterSymbol> inProgress) { var bounds = this.GetBounds(inProgress); return (bounds != null) ? bounds.DeducedBaseType : this.GetDefaultBaseType(); } internal ImmutableArray<SyntaxList<AttributeListSyntax>> MergedAttributeDeclarationSyntaxLists { get { var mergedAttributesBuilder = ArrayBuilder<SyntaxList<AttributeListSyntax>>.GetInstance(); foreach (var syntaxRef in _syntaxRefs) { var syntax = (TypeParameterSyntax)syntaxRef.GetSyntax(); mergedAttributesBuilder.Add(syntax.AttributeLists); } var sourceMethod = this.ContainingSymbol as SourceOrdinaryMethodSymbol; if ((object)sourceMethod != null && sourceMethod.IsPartial) { var implementingPart = sourceMethod.SourcePartialImplementation; if ((object)implementingPart != null) { var typeParameter = (SourceTypeParameterSymbolBase)implementingPart.TypeParameters[_ordinal]; mergedAttributesBuilder.AddRange(typeParameter.MergedAttributeDeclarationSyntaxLists); } } return mergedAttributesBuilder.ToImmutableAndFree(); } } IAttributeTargetSymbol IAttributeTargetSymbol.AttributesOwner { get { return this; } } AttributeLocation IAttributeTargetSymbol.DefaultAttributeLocation { get { return AttributeLocation.TypeParameter; } } AttributeLocation IAttributeTargetSymbol.AllowedAttributeLocations { get { return AttributeLocation.TypeParameter; } } /// <summary> /// Gets the attributes applied on this symbol. /// Returns an empty array if there are no attributes. /// </summary> /// <remarks> /// NOTE: This method should always be kept as a sealed override. /// If you want to override attribute binding logic for a sub-class, then override <see cref="GetAttributesBag"/> method. /// </remarks> public sealed override ImmutableArray<CSharpAttributeData> GetAttributes() { return this.GetAttributesBag().Attributes; } /// <summary> /// Returns a bag of applied custom attributes and data decoded from well-known attributes. Returns null if there are no attributes applied on the symbol. /// </summary> /// <remarks> /// Forces binding and decoding of attributes. /// </remarks> internal virtual CustomAttributesBag<CSharpAttributeData> GetAttributesBag() { if (_lazyCustomAttributesBag == null || !_lazyCustomAttributesBag.IsSealed) { bool lazyAttributesStored = false; var sourceMethod = this.ContainingSymbol as SourceOrdinaryMethodSymbol; if ((object)sourceMethod == null || (object)sourceMethod.SourcePartialDefinition == null) { lazyAttributesStored = LoadAndValidateAttributes( OneOrMany.Create(this.MergedAttributeDeclarationSyntaxLists), ref _lazyCustomAttributesBag, binderOpt: (ContainingSymbol as LocalFunctionSymbol)?.SignatureBinder); } else { var typeParameter = (SourceTypeParameterSymbolBase)sourceMethod.SourcePartialDefinition.TypeParameters[_ordinal]; CustomAttributesBag<CSharpAttributeData> attributesBag = typeParameter.GetAttributesBag(); lazyAttributesStored = Interlocked.CompareExchange(ref _lazyCustomAttributesBag, attributesBag, null) == null; } if (lazyAttributesStored) { _state.NotePartComplete(CompletionPart.Attributes); } } return _lazyCustomAttributesBag; } internal override void EnsureAllConstraintsAreResolved() { if (!_lazyBounds.IsSet()) { EnsureAllConstraintsAreResolved(this.ContainerTypeParameters); } } protected abstract ImmutableArray<TypeParameterSymbol> ContainerTypeParameters { get; } private TypeParameterBounds GetBounds(ConsList<TypeParameterSymbol> inProgress) { Debug.Assert(!inProgress.ContainsReference(this)); Debug.Assert(!inProgress.Any() || ReferenceEquals(inProgress.Head.ContainingSymbol, this.ContainingSymbol)); if (!_lazyBounds.IsSet()) { var diagnostics = BindingDiagnosticBag.GetInstance(); var bounds = this.ResolveBounds(inProgress, diagnostics); if (ReferenceEquals(Interlocked.CompareExchange(ref _lazyBounds, bounds, TypeParameterBounds.Unset), TypeParameterBounds.Unset)) { this.CheckConstraintTypeConstraints(diagnostics); this.CheckUnmanagedConstraint(diagnostics); this.EnsureAttributesFromConstraints(diagnostics); this.AddDeclarationDiagnostics(diagnostics); _state.NotePartComplete(CompletionPart.TypeParameterConstraints); } diagnostics.Free(); } return _lazyBounds; } protected abstract TypeParameterBounds ResolveBounds(ConsList<TypeParameterSymbol> inProgress, BindingDiagnosticBag diagnostics); /// <summary> /// Check constraints of generic types referenced in constraint types. For instance, /// with "interface I&lt;T&gt; where T : I&lt;T&gt; {}", check T satisfies constraints /// on I&lt;T&gt;. Those constraints are not checked when binding ConstraintTypes /// since ConstraintTypes has not been set on I&lt;T&gt; at that point. /// </summary> private void CheckConstraintTypeConstraints(BindingDiagnosticBag diagnostics) { var constraintTypes = this.ConstraintTypesNoUseSiteDiagnostics; if (constraintTypes.Length == 0) { return; } var args = new ConstraintsHelper.CheckConstraintsArgsBoxed(DeclaringCompilation, new TypeConversions(ContainingAssembly.CorLibrary), _locations[0], diagnostics); foreach (var constraintType in constraintTypes) { if (!diagnostics.ReportUseSite(constraintType.Type, args.Args.Location)) { constraintType.Type.CheckAllConstraints(args); } } } private void CheckUnmanagedConstraint(BindingDiagnosticBag diagnostics) { if (this.HasUnmanagedTypeConstraint) { DeclaringCompilation.EnsureIsUnmanagedAttributeExists(diagnostics, this.GetNonNullSyntaxNode().Location, ModifyCompilationForAttributeEmbedding()); } } private bool ModifyCompilationForAttributeEmbedding() { bool modifyCompilation; switch (this.ContainingSymbol) { case SourceOrdinaryMethodSymbol _: case SourceMemberContainerTypeSymbol _: modifyCompilation = true; break; case LocalFunctionSymbol _: modifyCompilation = false; break; default: throw ExceptionUtilities.UnexpectedValue(this.ContainingSymbol); } return modifyCompilation; } private void EnsureAttributesFromConstraints(BindingDiagnosticBag diagnostics) { if (ConstraintTypesNoUseSiteDiagnostics.Any(t => t.ContainsNativeInteger())) { DeclaringCompilation.EnsureNativeIntegerAttributeExists(diagnostics, getLocation(), ModifyCompilationForAttributeEmbedding()); } if (ConstraintsNeedNullableAttribute()) { DeclaringCompilation.EnsureNullableAttributeExists(diagnostics, getLocation(), ModifyCompilationForAttributeEmbedding()); } Location getLocation() => this.GetNonNullSyntaxNode().Location; } // See https://github.com/dotnet/roslyn/blob/main/docs/features/nullable-metadata.md internal bool ConstraintsNeedNullableAttribute() { if (!DeclaringCompilation.ShouldEmitNullableAttributes(this)) { return false; } if (this.HasReferenceTypeConstraint && this.ReferenceTypeConstraintIsNullable != null) { return true; } if (this.ConstraintTypesNoUseSiteDiagnostics.Any(c => c.NeedsNullableAttribute())) { return true; } if (this.HasNotNullConstraint) { return true; } return !this.HasReferenceTypeConstraint && !this.HasValueTypeConstraint && this.ConstraintTypesNoUseSiteDiagnostics.IsEmpty && this.IsNotNullable == false; } private NamedTypeSymbol GetDefaultBaseType() { return this.ContainingAssembly.GetSpecialType(SpecialType.System_Object); } internal override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) { while (true) { cancellationToken.ThrowIfCancellationRequested(); var incompletePart = _state.NextIncompletePart; switch (incompletePart) { case CompletionPart.Attributes: GetAttributes(); break; case CompletionPart.TypeParameterConstraints: var constraintTypes = this.ConstraintTypesNoUseSiteDiagnostics; // Nested type parameter references might not be valid in error scenarios. //Debug.Assert(this.ContainingSymbol.IsContainingSymbolOfAllTypeParameters(this.ConstraintTypes)); //Debug.Assert(this.ContainingSymbol.IsContainingSymbolOfAllTypeParameters(ImmutableArray<TypeSymbol>.CreateFrom(this.Interfaces))); Debug.Assert(this.ContainingSymbol.IsContainingSymbolOfAllTypeParameters(this.EffectiveBaseClassNoUseSiteDiagnostics)); Debug.Assert(this.ContainingSymbol.IsContainingSymbolOfAllTypeParameters(this.DeducedBaseTypeNoUseSiteDiagnostics)); break; case CompletionPart.None: return; default: // any other values are completion parts intended for other kinds of symbols _state.NotePartComplete(CompletionPart.All & ~CompletionPart.TypeParameterSymbolAll); break; } _state.SpinWaitComplete(incompletePart, cancellationToken); } } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); if (this.HasUnmanagedTypeConstraint) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeIsUnmanagedAttribute(this)); } var compilation = DeclaringCompilation; if (compilation.ShouldEmitNullableAttributes(this)) { AddSynthesizedAttribute( ref attributes, moduleBuilder.SynthesizeNullableAttributeIfNecessary(GetNullableContextValue(), GetSynthesizedNullableAttributeValue())); } } internal byte GetSynthesizedNullableAttributeValue() { if (this.HasReferenceTypeConstraint) { switch (this.ReferenceTypeConstraintIsNullable) { case true: return NullableAnnotationExtensions.AnnotatedAttributeValue; case false: return NullableAnnotationExtensions.NotAnnotatedAttributeValue; } } else if (this.HasNotNullConstraint) { return NullableAnnotationExtensions.NotAnnotatedAttributeValue; } else if (!this.HasValueTypeConstraint && this.ConstraintTypesNoUseSiteDiagnostics.IsEmpty && this.IsNotNullable == false) { return NullableAnnotationExtensions.AnnotatedAttributeValue; } return NullableAnnotationExtensions.ObliviousAttributeValue; } internal sealed override void DecodeWellKnownAttribute(ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments) { Debug.Assert((object)arguments.AttributeSyntaxOpt != null); Debug.Assert(arguments.Diagnostics is BindingDiagnosticBag); var attribute = arguments.Attribute; Debug.Assert(!attribute.HasErrors); Debug.Assert(arguments.SymbolPart == AttributeLocation.None); if (attribute.IsTargetAttribute(this, AttributeDescription.NullableAttribute)) { // NullableAttribute should not be set explicitly. ((BindingDiagnosticBag)arguments.Diagnostics).Add(ErrorCode.ERR_ExplicitNullableAttribute, arguments.AttributeSyntaxOpt.Location); } base.DecodeWellKnownAttribute(ref arguments); } protected bool? CalculateReferenceTypeConstraintIsNullable(TypeParameterConstraintKind constraints) { if ((constraints & TypeParameterConstraintKind.ReferenceType) == 0) { return false; } switch (constraints & TypeParameterConstraintKind.AllReferenceTypeKinds) { case TypeParameterConstraintKind.NullableReferenceType: return true; case TypeParameterConstraintKind.NotNullableReferenceType: return false; } return null; } } internal sealed class SourceTypeParameterSymbol : SourceTypeParameterSymbolBase { private readonly SourceNamedTypeSymbol _owner; private readonly VarianceKind _varianceKind; public SourceTypeParameterSymbol(SourceNamedTypeSymbol owner, string name, int ordinal, VarianceKind varianceKind, ImmutableArray<Location> locations, ImmutableArray<SyntaxReference> syntaxRefs) : base(name, ordinal, locations, syntaxRefs) { _owner = owner; _varianceKind = varianceKind; } public override TypeParameterKind TypeParameterKind { get { return TypeParameterKind.Type; } } public override Symbol ContainingSymbol { get { return _owner; } } public override VarianceKind Variance { get { return _varianceKind; } } public override bool HasConstructorConstraint { get { var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.Constructor) != 0; } } public override bool HasValueTypeConstraint { get { var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.AllValueTypeKinds) != 0; } } public override bool IsValueTypeFromConstraintTypes { get { Debug.Assert(!HasValueTypeConstraint); var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.ValueTypeFromConstraintTypes) != 0; } } public override bool HasReferenceTypeConstraint { get { var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.ReferenceType) != 0; } } public override bool IsReferenceTypeFromConstraintTypes { get { var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.ReferenceTypeFromConstraintTypes) != 0; } } internal override bool? ReferenceTypeConstraintIsNullable { get { return CalculateReferenceTypeConstraintIsNullable(this.GetConstraintKinds()); } } public override bool HasNotNullConstraint { get { var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.NotNull) != 0; } } internal override bool? IsNotNullable { get { if ((this.GetConstraintKinds() & TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType) != 0) { return null; } return CalculateIsNotNullable(); } } public override bool HasUnmanagedTypeConstraint { get { var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.Unmanaged) != 0; } } protected override ImmutableArray<TypeParameterSymbol> ContainerTypeParameters { get { return _owner.TypeParameters; } } protected override TypeParameterBounds ResolveBounds(ConsList<TypeParameterSymbol> inProgress, BindingDiagnosticBag diagnostics) { var constraintTypes = _owner.GetTypeParameterConstraintTypes(this.Ordinal); if (constraintTypes.IsEmpty && GetConstraintKinds() == TypeParameterConstraintKind.None) { return null; } return this.ResolveBounds(this.ContainingAssembly.CorLibrary, inProgress.Prepend(this), constraintTypes, inherited: false, this.DeclaringCompilation, diagnostics); } private TypeParameterConstraintKind GetConstraintKinds() { return _owner.GetTypeParameterConstraintKind(this.Ordinal); } } internal sealed class SourceMethodTypeParameterSymbol : SourceTypeParameterSymbolBase { private readonly SourceMethodSymbol _owner; public SourceMethodTypeParameterSymbol(SourceMethodSymbol owner, string name, int ordinal, ImmutableArray<Location> locations, ImmutableArray<SyntaxReference> syntaxRefs) : base(name, ordinal, locations, syntaxRefs) { _owner = owner; } internal override void AddDeclarationDiagnostics(BindingDiagnosticBag diagnostics) => _owner.AddDeclarationDiagnostics(diagnostics); public override TypeParameterKind TypeParameterKind { get { return TypeParameterKind.Method; } } public override Symbol ContainingSymbol { get { return _owner; } } public override bool HasConstructorConstraint { get { var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.Constructor) != 0; } } public override bool HasValueTypeConstraint { get { var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.AllValueTypeKinds) != 0; } } public override bool IsValueTypeFromConstraintTypes { get { Debug.Assert(!HasValueTypeConstraint); var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.ValueTypeFromConstraintTypes) != 0; } } public override bool HasReferenceTypeConstraint { get { var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.ReferenceType) != 0; } } public override bool IsReferenceTypeFromConstraintTypes { get { var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.ReferenceTypeFromConstraintTypes) != 0; } } public override bool HasNotNullConstraint { get { var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.NotNull) != 0; } } internal override bool? ReferenceTypeConstraintIsNullable { get { return CalculateReferenceTypeConstraintIsNullable(this.GetConstraintKinds()); } } internal override bool? IsNotNullable { get { if ((this.GetConstraintKinds() & TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType) != 0) { return null; } return CalculateIsNotNullable(); } } public override bool HasUnmanagedTypeConstraint { get { var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.Unmanaged) != 0; } } protected override ImmutableArray<TypeParameterSymbol> ContainerTypeParameters { get { return _owner.TypeParameters; } } protected override TypeParameterBounds ResolveBounds(ConsList<TypeParameterSymbol> inProgress, BindingDiagnosticBag diagnostics) { var constraints = _owner.GetTypeParameterConstraintTypes(); var constraintTypes = constraints.IsEmpty ? ImmutableArray<TypeWithAnnotations>.Empty : constraints[Ordinal]; if (constraintTypes.IsEmpty && GetConstraintKinds() == TypeParameterConstraintKind.None) { return null; } return this.ResolveBounds(this.ContainingAssembly.CorLibrary, inProgress.Prepend(this), constraintTypes, inherited: false, this.DeclaringCompilation, diagnostics); } private TypeParameterConstraintKind GetConstraintKinds() { var constraintKinds = _owner.GetTypeParameterConstraintKinds(); return constraintKinds.IsEmpty ? TypeParameterConstraintKind.None : constraintKinds[Ordinal]; } } /// <summary> /// A map shared by all type parameters for an overriding method or a method /// that explicitly implements an interface. The map caches the overridden method /// and a type map from overridden type parameters to overriding type parameters. /// </summary> internal abstract class OverriddenMethodTypeParameterMapBase { // Method representing overriding or explicit implementation. private readonly SourceOrdinaryMethodSymbol _overridingMethod; // Type map shared by all type parameters for this explicit implementation. private TypeMap _lazyTypeMap; // Overridden or explicitly implemented method. May be null in error cases. private MethodSymbol _lazyOverriddenMethod = ErrorMethodSymbol.UnknownMethod; protected OverriddenMethodTypeParameterMapBase(SourceOrdinaryMethodSymbol overridingMethod) { _overridingMethod = overridingMethod; } public SourceOrdinaryMethodSymbol OverridingMethod { get { return _overridingMethod; } } public TypeParameterSymbol GetOverriddenTypeParameter(int ordinal) { var overriddenMethod = this.OverriddenMethod; return ((object)overriddenMethod != null) ? overriddenMethod.TypeParameters[ordinal] : null; } public TypeMap TypeMap { get { if (_lazyTypeMap == null) { var overriddenMethod = this.OverriddenMethod; if ((object)overriddenMethod != null) { var overriddenTypeParameters = overriddenMethod.TypeParameters; var overridingTypeParameters = _overridingMethod.TypeParameters; Debug.Assert(overriddenTypeParameters.Length == overridingTypeParameters.Length); var typeMap = new TypeMap(overriddenTypeParameters, overridingTypeParameters, allowAlpha: true); Interlocked.CompareExchange(ref _lazyTypeMap, typeMap, null); } } return _lazyTypeMap; } } private MethodSymbol OverriddenMethod { get { if (ReferenceEquals(_lazyOverriddenMethod, ErrorMethodSymbol.UnknownMethod)) { Interlocked.CompareExchange(ref _lazyOverriddenMethod, this.GetOverriddenMethod(_overridingMethod), ErrorMethodSymbol.UnknownMethod); } return _lazyOverriddenMethod; } } protected abstract MethodSymbol GetOverriddenMethod(SourceOrdinaryMethodSymbol overridingMethod); } internal sealed class OverriddenMethodTypeParameterMap : OverriddenMethodTypeParameterMapBase { public OverriddenMethodTypeParameterMap(SourceOrdinaryMethodSymbol overridingMethod) : base(overridingMethod) { Debug.Assert(overridingMethod.IsOverride); } protected override MethodSymbol GetOverriddenMethod(SourceOrdinaryMethodSymbol overridingMethod) { MethodSymbol method = overridingMethod; Debug.Assert(method.IsOverride); do { method = method.OverriddenMethod; } while (((object)method != null) && method.IsOverride); // OverriddenMethod may be null in error situations. return method; } } internal sealed class ExplicitInterfaceMethodTypeParameterMap : OverriddenMethodTypeParameterMapBase { public ExplicitInterfaceMethodTypeParameterMap(SourceOrdinaryMethodSymbol implementationMethod) : base(implementationMethod) { Debug.Assert(implementationMethod.IsExplicitInterfaceImplementation); } protected override MethodSymbol GetOverriddenMethod(SourceOrdinaryMethodSymbol overridingMethod) { var explicitImplementations = overridingMethod.ExplicitInterfaceImplementations; Debug.Assert(explicitImplementations.Length <= 1); // ExplicitInterfaceImplementations may be empty in error situations. return (explicitImplementations.Length > 0) ? explicitImplementations[0] : null; } } /// <summary> /// A type parameter for a method that either overrides a base /// type method or explicitly implements an interface method. /// </summary> /// <remarks> /// Exists to copy constraints from the corresponding type parameter of an overridden method. /// </remarks> internal sealed class SourceOverridingMethodTypeParameterSymbol : SourceTypeParameterSymbolBase { private readonly OverriddenMethodTypeParameterMapBase _map; public SourceOverridingMethodTypeParameterSymbol(OverriddenMethodTypeParameterMapBase map, string name, int ordinal, ImmutableArray<Location> locations, ImmutableArray<SyntaxReference> syntaxRefs) : base(name, ordinal, locations, syntaxRefs) { _map = map; } public SourceOrdinaryMethodSymbol Owner { get { return _map.OverridingMethod; } } public override TypeParameterKind TypeParameterKind { get { return TypeParameterKind.Method; } } public override Symbol ContainingSymbol { get { return this.Owner; } } public override bool HasConstructorConstraint { get { var typeParameter = this.OverriddenTypeParameter; return ((object)typeParameter != null) && typeParameter.HasConstructorConstraint; } } public override bool HasValueTypeConstraint { get { var typeParameter = this.OverriddenTypeParameter; return ((object)typeParameter != null) && typeParameter.HasValueTypeConstraint; } } public override bool IsValueTypeFromConstraintTypes { get { var typeParameter = this.OverriddenTypeParameter; return ((object)typeParameter != null) && (typeParameter.IsValueTypeFromConstraintTypes || CalculateIsValueTypeFromConstraintTypes(ConstraintTypesNoUseSiteDiagnostics)); } } public override bool HasReferenceTypeConstraint { get { var typeParameter = this.OverriddenTypeParameter; return ((object)typeParameter != null) && typeParameter.HasReferenceTypeConstraint; } } public override bool IsReferenceTypeFromConstraintTypes { get { var typeParameter = this.OverriddenTypeParameter; return ((object)typeParameter != null) && (typeParameter.IsReferenceTypeFromConstraintTypes || CalculateIsReferenceTypeFromConstraintTypes(ConstraintTypesNoUseSiteDiagnostics)); } } internal override bool? ReferenceTypeConstraintIsNullable { get { TypeParameterSymbol typeParameter = this.OverriddenTypeParameter; return ((object)typeParameter != null) ? typeParameter.ReferenceTypeConstraintIsNullable : false; } } public override bool HasNotNullConstraint { get { return this.OverriddenTypeParameter?.HasNotNullConstraint == true; } } internal override bool? IsNotNullable { get { return this.OverriddenTypeParameter?.IsNotNullable; } } public override bool HasUnmanagedTypeConstraint { get { var typeParameter = this.OverriddenTypeParameter; return ((object)typeParameter != null) && typeParameter.HasUnmanagedTypeConstraint; } } protected override ImmutableArray<TypeParameterSymbol> ContainerTypeParameters { get { return this.Owner.TypeParameters; } } protected override TypeParameterBounds ResolveBounds(ConsList<TypeParameterSymbol> inProgress, BindingDiagnosticBag diagnostics) { var typeParameter = this.OverriddenTypeParameter; if ((object)typeParameter == null) { return null; } var map = _map.TypeMap; Debug.Assert(map != null); var constraintTypes = map.SubstituteTypes(typeParameter.ConstraintTypesNoUseSiteDiagnostics); return this.ResolveBounds(this.ContainingAssembly.CorLibrary, inProgress.Prepend(this), constraintTypes, inherited: true, this.DeclaringCompilation, diagnostics); } /// <summary> /// The type parameter to use for determining constraints. If there is a base /// method that the owner method is overriding, the corresponding type /// parameter on that method is used. Otherwise, the result is null. /// </summary> private TypeParameterSymbol OverriddenTypeParameter { get { return _map.GetOverriddenTypeParameter(this.Ordinal); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Base class for type and method type parameters. /// </summary> internal abstract class SourceTypeParameterSymbolBase : TypeParameterSymbol, IAttributeTargetSymbol { private readonly ImmutableArray<SyntaxReference> _syntaxRefs; private readonly ImmutableArray<Location> _locations; private readonly string _name; private readonly short _ordinal; private SymbolCompletionState _state; private CustomAttributesBag<CSharpAttributeData> _lazyCustomAttributesBag; private TypeParameterBounds _lazyBounds = TypeParameterBounds.Unset; protected SourceTypeParameterSymbolBase(string name, int ordinal, ImmutableArray<Location> locations, ImmutableArray<SyntaxReference> syntaxRefs) { Debug.Assert(!syntaxRefs.IsEmpty); _name = name; _ordinal = (short)ordinal; _locations = locations; _syntaxRefs = syntaxRefs; } public override ImmutableArray<Location> Locations { get { return _locations; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return _syntaxRefs; } } internal ImmutableArray<SyntaxReference> SyntaxReferences { get { return _syntaxRefs; } } public override int Ordinal { get { return _ordinal; } } public override VarianceKind Variance { get { return VarianceKind.None; } } public override string Name { get { return _name; } } internal override ImmutableArray<TypeWithAnnotations> GetConstraintTypes(ConsList<TypeParameterSymbol> inProgress) { var bounds = this.GetBounds(inProgress); return (bounds != null) ? bounds.ConstraintTypes : ImmutableArray<TypeWithAnnotations>.Empty; } internal override ImmutableArray<NamedTypeSymbol> GetInterfaces(ConsList<TypeParameterSymbol> inProgress) { var bounds = this.GetBounds(inProgress); return (bounds != null) ? bounds.Interfaces : ImmutableArray<NamedTypeSymbol>.Empty; } internal override NamedTypeSymbol GetEffectiveBaseClass(ConsList<TypeParameterSymbol> inProgress) { var bounds = this.GetBounds(inProgress); return (bounds != null) ? bounds.EffectiveBaseClass : this.GetDefaultBaseType(); } internal override TypeSymbol GetDeducedBaseType(ConsList<TypeParameterSymbol> inProgress) { var bounds = this.GetBounds(inProgress); return (bounds != null) ? bounds.DeducedBaseType : this.GetDefaultBaseType(); } internal ImmutableArray<SyntaxList<AttributeListSyntax>> MergedAttributeDeclarationSyntaxLists { get { var mergedAttributesBuilder = ArrayBuilder<SyntaxList<AttributeListSyntax>>.GetInstance(); foreach (var syntaxRef in _syntaxRefs) { var syntax = (TypeParameterSyntax)syntaxRef.GetSyntax(); mergedAttributesBuilder.Add(syntax.AttributeLists); } var sourceMethod = this.ContainingSymbol as SourceOrdinaryMethodSymbol; if ((object)sourceMethod != null && sourceMethod.IsPartial) { var implementingPart = sourceMethod.SourcePartialImplementation; if ((object)implementingPart != null) { var typeParameter = (SourceTypeParameterSymbolBase)implementingPart.TypeParameters[_ordinal]; mergedAttributesBuilder.AddRange(typeParameter.MergedAttributeDeclarationSyntaxLists); } } return mergedAttributesBuilder.ToImmutableAndFree(); } } IAttributeTargetSymbol IAttributeTargetSymbol.AttributesOwner { get { return this; } } AttributeLocation IAttributeTargetSymbol.DefaultAttributeLocation { get { return AttributeLocation.TypeParameter; } } AttributeLocation IAttributeTargetSymbol.AllowedAttributeLocations { get { return AttributeLocation.TypeParameter; } } /// <summary> /// Gets the attributes applied on this symbol. /// Returns an empty array if there are no attributes. /// </summary> /// <remarks> /// NOTE: This method should always be kept as a sealed override. /// If you want to override attribute binding logic for a sub-class, then override <see cref="GetAttributesBag"/> method. /// </remarks> public sealed override ImmutableArray<CSharpAttributeData> GetAttributes() { return this.GetAttributesBag().Attributes; } /// <summary> /// Returns a bag of applied custom attributes and data decoded from well-known attributes. Returns null if there are no attributes applied on the symbol. /// </summary> /// <remarks> /// Forces binding and decoding of attributes. /// </remarks> internal virtual CustomAttributesBag<CSharpAttributeData> GetAttributesBag() { if (_lazyCustomAttributesBag == null || !_lazyCustomAttributesBag.IsSealed) { bool lazyAttributesStored = false; var sourceMethod = this.ContainingSymbol as SourceOrdinaryMethodSymbol; if ((object)sourceMethod == null || (object)sourceMethod.SourcePartialDefinition == null) { lazyAttributesStored = LoadAndValidateAttributes( OneOrMany.Create(this.MergedAttributeDeclarationSyntaxLists), ref _lazyCustomAttributesBag, binderOpt: (ContainingSymbol as LocalFunctionSymbol)?.SignatureBinder); } else { var typeParameter = (SourceTypeParameterSymbolBase)sourceMethod.SourcePartialDefinition.TypeParameters[_ordinal]; CustomAttributesBag<CSharpAttributeData> attributesBag = typeParameter.GetAttributesBag(); lazyAttributesStored = Interlocked.CompareExchange(ref _lazyCustomAttributesBag, attributesBag, null) == null; } if (lazyAttributesStored) { _state.NotePartComplete(CompletionPart.Attributes); } } return _lazyCustomAttributesBag; } internal override void EnsureAllConstraintsAreResolved() { if (!_lazyBounds.IsSet()) { EnsureAllConstraintsAreResolved(this.ContainerTypeParameters); } } protected abstract ImmutableArray<TypeParameterSymbol> ContainerTypeParameters { get; } private TypeParameterBounds GetBounds(ConsList<TypeParameterSymbol> inProgress) { Debug.Assert(!inProgress.ContainsReference(this)); Debug.Assert(!inProgress.Any() || ReferenceEquals(inProgress.Head.ContainingSymbol, this.ContainingSymbol)); if (!_lazyBounds.IsSet()) { var diagnostics = BindingDiagnosticBag.GetInstance(); var bounds = this.ResolveBounds(inProgress, diagnostics); if (ReferenceEquals(Interlocked.CompareExchange(ref _lazyBounds, bounds, TypeParameterBounds.Unset), TypeParameterBounds.Unset)) { this.CheckConstraintTypeConstraints(diagnostics); this.CheckUnmanagedConstraint(diagnostics); this.EnsureAttributesFromConstraints(diagnostics); this.AddDeclarationDiagnostics(diagnostics); _state.NotePartComplete(CompletionPart.TypeParameterConstraints); } diagnostics.Free(); } return _lazyBounds; } protected abstract TypeParameterBounds ResolveBounds(ConsList<TypeParameterSymbol> inProgress, BindingDiagnosticBag diagnostics); /// <summary> /// Check constraints of generic types referenced in constraint types. For instance, /// with "interface I&lt;T&gt; where T : I&lt;T&gt; {}", check T satisfies constraints /// on I&lt;T&gt;. Those constraints are not checked when binding ConstraintTypes /// since ConstraintTypes has not been set on I&lt;T&gt; at that point. /// </summary> private void CheckConstraintTypeConstraints(BindingDiagnosticBag diagnostics) { var constraintTypes = this.ConstraintTypesNoUseSiteDiagnostics; if (constraintTypes.Length == 0) { return; } var args = new ConstraintsHelper.CheckConstraintsArgsBoxed(DeclaringCompilation, new TypeConversions(ContainingAssembly.CorLibrary), _locations[0], diagnostics); foreach (var constraintType in constraintTypes) { if (!diagnostics.ReportUseSite(constraintType.Type, args.Args.Location)) { constraintType.Type.CheckAllConstraints(args); } } } private void CheckUnmanagedConstraint(BindingDiagnosticBag diagnostics) { if (this.HasUnmanagedTypeConstraint) { DeclaringCompilation.EnsureIsUnmanagedAttributeExists(diagnostics, this.GetNonNullSyntaxNode().Location, ModifyCompilationForAttributeEmbedding()); } } private bool ModifyCompilationForAttributeEmbedding() { bool modifyCompilation; switch (this.ContainingSymbol) { case SourceOrdinaryMethodSymbol _: case SourceMemberContainerTypeSymbol _: modifyCompilation = true; break; case LocalFunctionSymbol _: modifyCompilation = false; break; default: throw ExceptionUtilities.UnexpectedValue(this.ContainingSymbol); } return modifyCompilation; } private void EnsureAttributesFromConstraints(BindingDiagnosticBag diagnostics) { if (ConstraintTypesNoUseSiteDiagnostics.Any(t => t.ContainsNativeInteger())) { DeclaringCompilation.EnsureNativeIntegerAttributeExists(diagnostics, getLocation(), ModifyCompilationForAttributeEmbedding()); } if (ConstraintsNeedNullableAttribute()) { DeclaringCompilation.EnsureNullableAttributeExists(diagnostics, getLocation(), ModifyCompilationForAttributeEmbedding()); } Location getLocation() => this.GetNonNullSyntaxNode().Location; } // See https://github.com/dotnet/roslyn/blob/main/docs/features/nullable-metadata.md internal bool ConstraintsNeedNullableAttribute() { if (!DeclaringCompilation.ShouldEmitNullableAttributes(this)) { return false; } if (this.HasReferenceTypeConstraint && this.ReferenceTypeConstraintIsNullable != null) { return true; } if (this.ConstraintTypesNoUseSiteDiagnostics.Any(c => c.NeedsNullableAttribute())) { return true; } if (this.HasNotNullConstraint) { return true; } return !this.HasReferenceTypeConstraint && !this.HasValueTypeConstraint && this.ConstraintTypesNoUseSiteDiagnostics.IsEmpty && this.IsNotNullable == false; } private NamedTypeSymbol GetDefaultBaseType() { return this.ContainingAssembly.GetSpecialType(SpecialType.System_Object); } internal override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) { while (true) { cancellationToken.ThrowIfCancellationRequested(); var incompletePart = _state.NextIncompletePart; switch (incompletePart) { case CompletionPart.Attributes: GetAttributes(); break; case CompletionPart.TypeParameterConstraints: var constraintTypes = this.ConstraintTypesNoUseSiteDiagnostics; // Nested type parameter references might not be valid in error scenarios. //Debug.Assert(this.ContainingSymbol.IsContainingSymbolOfAllTypeParameters(this.ConstraintTypes)); //Debug.Assert(this.ContainingSymbol.IsContainingSymbolOfAllTypeParameters(ImmutableArray<TypeSymbol>.CreateFrom(this.Interfaces))); Debug.Assert(this.ContainingSymbol.IsContainingSymbolOfAllTypeParameters(this.EffectiveBaseClassNoUseSiteDiagnostics)); Debug.Assert(this.ContainingSymbol.IsContainingSymbolOfAllTypeParameters(this.DeducedBaseTypeNoUseSiteDiagnostics)); break; case CompletionPart.None: return; default: // any other values are completion parts intended for other kinds of symbols _state.NotePartComplete(CompletionPart.All & ~CompletionPart.TypeParameterSymbolAll); break; } _state.SpinWaitComplete(incompletePart, cancellationToken); } } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); if (this.HasUnmanagedTypeConstraint) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeIsUnmanagedAttribute(this)); } var compilation = DeclaringCompilation; if (compilation.ShouldEmitNullableAttributes(this)) { AddSynthesizedAttribute( ref attributes, moduleBuilder.SynthesizeNullableAttributeIfNecessary(GetNullableContextValue(), GetSynthesizedNullableAttributeValue())); } } internal byte GetSynthesizedNullableAttributeValue() { if (this.HasReferenceTypeConstraint) { switch (this.ReferenceTypeConstraintIsNullable) { case true: return NullableAnnotationExtensions.AnnotatedAttributeValue; case false: return NullableAnnotationExtensions.NotAnnotatedAttributeValue; } } else if (this.HasNotNullConstraint) { return NullableAnnotationExtensions.NotAnnotatedAttributeValue; } else if (!this.HasValueTypeConstraint && this.ConstraintTypesNoUseSiteDiagnostics.IsEmpty && this.IsNotNullable == false) { return NullableAnnotationExtensions.AnnotatedAttributeValue; } return NullableAnnotationExtensions.ObliviousAttributeValue; } internal sealed override void DecodeWellKnownAttribute(ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments) { Debug.Assert((object)arguments.AttributeSyntaxOpt != null); Debug.Assert(arguments.Diagnostics is BindingDiagnosticBag); var attribute = arguments.Attribute; Debug.Assert(!attribute.HasErrors); Debug.Assert(arguments.SymbolPart == AttributeLocation.None); if (attribute.IsTargetAttribute(this, AttributeDescription.NullableAttribute)) { // NullableAttribute should not be set explicitly. ((BindingDiagnosticBag)arguments.Diagnostics).Add(ErrorCode.ERR_ExplicitNullableAttribute, arguments.AttributeSyntaxOpt.Location); } base.DecodeWellKnownAttribute(ref arguments); } protected bool? CalculateReferenceTypeConstraintIsNullable(TypeParameterConstraintKind constraints) { if ((constraints & TypeParameterConstraintKind.ReferenceType) == 0) { return false; } switch (constraints & TypeParameterConstraintKind.AllReferenceTypeKinds) { case TypeParameterConstraintKind.NullableReferenceType: return true; case TypeParameterConstraintKind.NotNullableReferenceType: return false; } return null; } } internal sealed class SourceTypeParameterSymbol : SourceTypeParameterSymbolBase { private readonly SourceNamedTypeSymbol _owner; private readonly VarianceKind _varianceKind; public SourceTypeParameterSymbol(SourceNamedTypeSymbol owner, string name, int ordinal, VarianceKind varianceKind, ImmutableArray<Location> locations, ImmutableArray<SyntaxReference> syntaxRefs) : base(name, ordinal, locations, syntaxRefs) { _owner = owner; _varianceKind = varianceKind; } public override TypeParameterKind TypeParameterKind { get { return TypeParameterKind.Type; } } public override Symbol ContainingSymbol { get { return _owner; } } public override VarianceKind Variance { get { return _varianceKind; } } public override bool HasConstructorConstraint { get { var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.Constructor) != 0; } } public override bool HasValueTypeConstraint { get { var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.AllValueTypeKinds) != 0; } } public override bool IsValueTypeFromConstraintTypes { get { Debug.Assert(!HasValueTypeConstraint); var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.ValueTypeFromConstraintTypes) != 0; } } public override bool HasReferenceTypeConstraint { get { var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.ReferenceType) != 0; } } public override bool IsReferenceTypeFromConstraintTypes { get { var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.ReferenceTypeFromConstraintTypes) != 0; } } internal override bool? ReferenceTypeConstraintIsNullable { get { return CalculateReferenceTypeConstraintIsNullable(this.GetConstraintKinds()); } } public override bool HasNotNullConstraint { get { var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.NotNull) != 0; } } internal override bool? IsNotNullable { get { if ((this.GetConstraintKinds() & TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType) != 0) { return null; } return CalculateIsNotNullable(); } } public override bool HasUnmanagedTypeConstraint { get { var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.Unmanaged) != 0; } } protected override ImmutableArray<TypeParameterSymbol> ContainerTypeParameters { get { return _owner.TypeParameters; } } protected override TypeParameterBounds ResolveBounds(ConsList<TypeParameterSymbol> inProgress, BindingDiagnosticBag diagnostics) { var constraintTypes = _owner.GetTypeParameterConstraintTypes(this.Ordinal); if (constraintTypes.IsEmpty && GetConstraintKinds() == TypeParameterConstraintKind.None) { return null; } return this.ResolveBounds(this.ContainingAssembly.CorLibrary, inProgress.Prepend(this), constraintTypes, inherited: false, this.DeclaringCompilation, diagnostics); } private TypeParameterConstraintKind GetConstraintKinds() { return _owner.GetTypeParameterConstraintKind(this.Ordinal); } } internal sealed class SourceMethodTypeParameterSymbol : SourceTypeParameterSymbolBase { private readonly SourceMethodSymbol _owner; public SourceMethodTypeParameterSymbol(SourceMethodSymbol owner, string name, int ordinal, ImmutableArray<Location> locations, ImmutableArray<SyntaxReference> syntaxRefs) : base(name, ordinal, locations, syntaxRefs) { _owner = owner; } internal override void AddDeclarationDiagnostics(BindingDiagnosticBag diagnostics) => _owner.AddDeclarationDiagnostics(diagnostics); public override TypeParameterKind TypeParameterKind { get { return TypeParameterKind.Method; } } public override Symbol ContainingSymbol { get { return _owner; } } public override bool HasConstructorConstraint { get { var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.Constructor) != 0; } } public override bool HasValueTypeConstraint { get { var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.AllValueTypeKinds) != 0; } } public override bool IsValueTypeFromConstraintTypes { get { Debug.Assert(!HasValueTypeConstraint); var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.ValueTypeFromConstraintTypes) != 0; } } public override bool HasReferenceTypeConstraint { get { var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.ReferenceType) != 0; } } public override bool IsReferenceTypeFromConstraintTypes { get { var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.ReferenceTypeFromConstraintTypes) != 0; } } public override bool HasNotNullConstraint { get { var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.NotNull) != 0; } } internal override bool? ReferenceTypeConstraintIsNullable { get { return CalculateReferenceTypeConstraintIsNullable(this.GetConstraintKinds()); } } internal override bool? IsNotNullable { get { if ((this.GetConstraintKinds() & TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType) != 0) { return null; } return CalculateIsNotNullable(); } } public override bool HasUnmanagedTypeConstraint { get { var constraints = this.GetConstraintKinds(); return (constraints & TypeParameterConstraintKind.Unmanaged) != 0; } } protected override ImmutableArray<TypeParameterSymbol> ContainerTypeParameters { get { return _owner.TypeParameters; } } protected override TypeParameterBounds ResolveBounds(ConsList<TypeParameterSymbol> inProgress, BindingDiagnosticBag diagnostics) { var constraints = _owner.GetTypeParameterConstraintTypes(); var constraintTypes = constraints.IsEmpty ? ImmutableArray<TypeWithAnnotations>.Empty : constraints[Ordinal]; if (constraintTypes.IsEmpty && GetConstraintKinds() == TypeParameterConstraintKind.None) { return null; } return this.ResolveBounds(this.ContainingAssembly.CorLibrary, inProgress.Prepend(this), constraintTypes, inherited: false, this.DeclaringCompilation, diagnostics); } private TypeParameterConstraintKind GetConstraintKinds() { var constraintKinds = _owner.GetTypeParameterConstraintKinds(); return constraintKinds.IsEmpty ? TypeParameterConstraintKind.None : constraintKinds[Ordinal]; } } /// <summary> /// A map shared by all type parameters for an overriding method or a method /// that explicitly implements an interface. The map caches the overridden method /// and a type map from overridden type parameters to overriding type parameters. /// </summary> internal abstract class OverriddenMethodTypeParameterMapBase { // Method representing overriding or explicit implementation. private readonly SourceOrdinaryMethodSymbol _overridingMethod; // Type map shared by all type parameters for this explicit implementation. private TypeMap _lazyTypeMap; // Overridden or explicitly implemented method. May be null in error cases. private MethodSymbol _lazyOverriddenMethod = ErrorMethodSymbol.UnknownMethod; protected OverriddenMethodTypeParameterMapBase(SourceOrdinaryMethodSymbol overridingMethod) { _overridingMethod = overridingMethod; } public SourceOrdinaryMethodSymbol OverridingMethod { get { return _overridingMethod; } } public TypeParameterSymbol GetOverriddenTypeParameter(int ordinal) { var overriddenMethod = this.OverriddenMethod; return ((object)overriddenMethod != null) ? overriddenMethod.TypeParameters[ordinal] : null; } public TypeMap TypeMap { get { if (_lazyTypeMap == null) { var overriddenMethod = this.OverriddenMethod; if ((object)overriddenMethod != null) { var overriddenTypeParameters = overriddenMethod.TypeParameters; var overridingTypeParameters = _overridingMethod.TypeParameters; Debug.Assert(overriddenTypeParameters.Length == overridingTypeParameters.Length); var typeMap = new TypeMap(overriddenTypeParameters, overridingTypeParameters, allowAlpha: true); Interlocked.CompareExchange(ref _lazyTypeMap, typeMap, null); } } return _lazyTypeMap; } } private MethodSymbol OverriddenMethod { get { if (ReferenceEquals(_lazyOverriddenMethod, ErrorMethodSymbol.UnknownMethod)) { Interlocked.CompareExchange(ref _lazyOverriddenMethod, this.GetOverriddenMethod(_overridingMethod), ErrorMethodSymbol.UnknownMethod); } return _lazyOverriddenMethod; } } protected abstract MethodSymbol GetOverriddenMethod(SourceOrdinaryMethodSymbol overridingMethod); } internal sealed class OverriddenMethodTypeParameterMap : OverriddenMethodTypeParameterMapBase { public OverriddenMethodTypeParameterMap(SourceOrdinaryMethodSymbol overridingMethod) : base(overridingMethod) { Debug.Assert(overridingMethod.IsOverride); } protected override MethodSymbol GetOverriddenMethod(SourceOrdinaryMethodSymbol overridingMethod) { MethodSymbol method = overridingMethod; Debug.Assert(method.IsOverride); do { method = method.OverriddenMethod; } while (((object)method != null) && method.IsOverride); // OverriddenMethod may be null in error situations. return method; } } internal sealed class ExplicitInterfaceMethodTypeParameterMap : OverriddenMethodTypeParameterMapBase { public ExplicitInterfaceMethodTypeParameterMap(SourceOrdinaryMethodSymbol implementationMethod) : base(implementationMethod) { Debug.Assert(implementationMethod.IsExplicitInterfaceImplementation); } protected override MethodSymbol GetOverriddenMethod(SourceOrdinaryMethodSymbol overridingMethod) { var explicitImplementations = overridingMethod.ExplicitInterfaceImplementations; Debug.Assert(explicitImplementations.Length <= 1); // ExplicitInterfaceImplementations may be empty in error situations. return (explicitImplementations.Length > 0) ? explicitImplementations[0] : null; } } /// <summary> /// A type parameter for a method that either overrides a base /// type method or explicitly implements an interface method. /// </summary> /// <remarks> /// Exists to copy constraints from the corresponding type parameter of an overridden method. /// </remarks> internal sealed class SourceOverridingMethodTypeParameterSymbol : SourceTypeParameterSymbolBase { private readonly OverriddenMethodTypeParameterMapBase _map; public SourceOverridingMethodTypeParameterSymbol(OverriddenMethodTypeParameterMapBase map, string name, int ordinal, ImmutableArray<Location> locations, ImmutableArray<SyntaxReference> syntaxRefs) : base(name, ordinal, locations, syntaxRefs) { _map = map; } public SourceOrdinaryMethodSymbol Owner { get { return _map.OverridingMethod; } } public override TypeParameterKind TypeParameterKind { get { return TypeParameterKind.Method; } } public override Symbol ContainingSymbol { get { return this.Owner; } } public override bool HasConstructorConstraint { get { var typeParameter = this.OverriddenTypeParameter; return ((object)typeParameter != null) && typeParameter.HasConstructorConstraint; } } public override bool HasValueTypeConstraint { get { var typeParameter = this.OverriddenTypeParameter; return ((object)typeParameter != null) && typeParameter.HasValueTypeConstraint; } } public override bool IsValueTypeFromConstraintTypes { get { var typeParameter = this.OverriddenTypeParameter; return ((object)typeParameter != null) && (typeParameter.IsValueTypeFromConstraintTypes || CalculateIsValueTypeFromConstraintTypes(ConstraintTypesNoUseSiteDiagnostics)); } } public override bool HasReferenceTypeConstraint { get { var typeParameter = this.OverriddenTypeParameter; return ((object)typeParameter != null) && typeParameter.HasReferenceTypeConstraint; } } public override bool IsReferenceTypeFromConstraintTypes { get { var typeParameter = this.OverriddenTypeParameter; return ((object)typeParameter != null) && (typeParameter.IsReferenceTypeFromConstraintTypes || CalculateIsReferenceTypeFromConstraintTypes(ConstraintTypesNoUseSiteDiagnostics)); } } internal override bool? ReferenceTypeConstraintIsNullable { get { TypeParameterSymbol typeParameter = this.OverriddenTypeParameter; return ((object)typeParameter != null) ? typeParameter.ReferenceTypeConstraintIsNullable : false; } } public override bool HasNotNullConstraint { get { return this.OverriddenTypeParameter?.HasNotNullConstraint == true; } } internal override bool? IsNotNullable { get { return this.OverriddenTypeParameter?.IsNotNullable; } } public override bool HasUnmanagedTypeConstraint { get { var typeParameter = this.OverriddenTypeParameter; return ((object)typeParameter != null) && typeParameter.HasUnmanagedTypeConstraint; } } protected override ImmutableArray<TypeParameterSymbol> ContainerTypeParameters { get { return this.Owner.TypeParameters; } } protected override TypeParameterBounds ResolveBounds(ConsList<TypeParameterSymbol> inProgress, BindingDiagnosticBag diagnostics) { var typeParameter = this.OverriddenTypeParameter; if ((object)typeParameter == null) { return null; } var map = _map.TypeMap; Debug.Assert(map != null); var constraintTypes = map.SubstituteTypes(typeParameter.ConstraintTypesNoUseSiteDiagnostics); return this.ResolveBounds(this.ContainingAssembly.CorLibrary, inProgress.Prepend(this), constraintTypes, inherited: true, this.DeclaringCompilation, diagnostics); } /// <summary> /// The type parameter to use for determining constraints. If there is a base /// method that the owner method is overriding, the corresponding type /// parameter on that method is used. Otherwise, the result is null. /// </summary> private TypeParameterSymbol OverriddenTypeParameter { get { return _map.GetOverriddenTypeParameter(this.Ordinal); } } } }
-1
dotnet/roslyn
55,419
Make vsix's compatible with vs 2022
Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
dibarbet
2021-08-04T23:36:41Z
2021-08-06T17:54:08Z
082df2aaf6a73277fc27f9d7a5a8d18ee45d7f8b
e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028
Make vsix's compatible with vs 2022. Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
./src/Compilers/VisualBasic/Portable/Emit/AttributeDataAdapter.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Emit Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Partial Friend Class VisualBasicAttributeData Implements Cci.ICustomAttribute Private Function GetArguments1(context As EmitContext) As ImmutableArray(Of Cci.IMetadataExpression) Implements Cci.ICustomAttribute.GetArguments Return CommonConstructorArguments.SelectAsArray(Function(arg) CreateMetadataExpression(arg, context)) End Function Private Function Constructor1(context As EmitContext, reportDiagnostics As Boolean) As Cci.IMethodReference Implements Cci.ICustomAttribute.Constructor If Me.AttributeConstructor.IsDefaultValueTypeConstructor() Then ' Parameter constructors for structs exist in symbol table, but are not emitted. ' Produce an error since we cannot use it (instead of crashing): ' Details: https://github.com/dotnet/roslyn/issues/19394 If reportDiagnostics Then context.Diagnostics.Add(ERRID.ERR_AttributeMustBeClassNotStruct1, If(context.SyntaxNode?.GetLocation(), NoLocation.Singleton), Me.AttributeClass) End If Return Nothing End If Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(context.Module, PEModuleBuilder) Return moduleBeingBuilt.Translate(AttributeConstructor, needDeclaration:=False, syntaxNodeOpt:=DirectCast(context.SyntaxNode, VisualBasicSyntaxNode), diagnostics:=context.Diagnostics) End Function Private Function GetNamedArguments1(context As EmitContext) As ImmutableArray(Of Cci.IMetadataNamedArgument) Implements Cci.ICustomAttribute.GetNamedArguments Return CommonNamedArguments.SelectAsArray(Function(namedArgument) CreateMetadataNamedArgument(namedArgument.Key, namedArgument.Value, context)) End Function Private ReadOnly Property ArgumentCount As Integer Implements Cci.ICustomAttribute.ArgumentCount Get Return CommonConstructorArguments.Length End Get End Property Private ReadOnly Property NamedArgumentCount As UShort Implements Cci.ICustomAttribute.NamedArgumentCount Get Return CType(CommonNamedArguments.Length, UShort) End Get End Property Private Function GetType1(context As EmitContext) As Cci.ITypeReference Implements Cci.ICustomAttribute.GetType Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(context.Module, PEModuleBuilder) Return moduleBeingBuilt.Translate(AttributeClass, syntaxNodeOpt:=DirectCast(context.SyntaxNode, VisualBasicSyntaxNode), diagnostics:=context.Diagnostics) End Function Private ReadOnly Property AllowMultiple1 As Boolean Implements Cci.ICustomAttribute.AllowMultiple Get Return Me.AttributeClass.GetAttributeUsageInfo().AllowMultiple End Get End Property Private Function CreateMetadataExpression(argument As TypedConstant, context As EmitContext) As Cci.IMetadataExpression If argument.IsNull Then Return CreateMetadataConstant(argument.TypeInternal, Nothing, context) End If Select Case argument.Kind Case TypedConstantKind.Array Return CreateMetadataArray(argument, context) Case TypedConstantKind.Type Return CreateType(argument, context) Case Else Return CreateMetadataConstant(argument.TypeInternal, argument.ValueInternal, context) End Select End Function Private Function CreateMetadataArray(argument As TypedConstant, context As EmitContext) As MetadataCreateArray Debug.Assert(Not argument.Values.IsDefault) Dim values = argument.Values Dim moduleBeingBuilt = DirectCast(context.Module, PEModuleBuilder) Dim arrayType = moduleBeingBuilt.Translate(DirectCast(argument.TypeInternal, ArrayTypeSymbol)) If values.Length = 0 Then Return New MetadataCreateArray(arrayType, arrayType.GetElementType(context), ImmutableArray(Of Cci.IMetadataExpression).Empty) End If Dim metadataExprs = New Cci.IMetadataExpression(values.Length - 1) {} For i = 0 To values.Length - 1 metadataExprs(i) = CreateMetadataExpression(values(i), context) Next Return New MetadataCreateArray(arrayType, arrayType.GetElementType(context), metadataExprs.AsImmutableOrNull) End Function Private Function CreateType(argument As TypedConstant, context As EmitContext) As MetadataTypeOf Debug.Assert(argument.ValueInternal IsNot Nothing) Dim moduleBeingBuilt = DirectCast(context.Module, PEModuleBuilder) Dim syntaxNodeOpt = DirectCast(context.SyntaxNode, VisualBasicSyntaxNode) Dim diagnostics = context.Diagnostics Return New MetadataTypeOf(moduleBeingBuilt.Translate(DirectCast(argument.ValueInternal, TypeSymbol), syntaxNodeOpt, diagnostics), moduleBeingBuilt.Translate(DirectCast(argument.TypeInternal, TypeSymbol), syntaxNodeOpt, diagnostics)) End Function Private Function CreateMetadataConstant(type As ITypeSymbolInternal, value As Object, context As EmitContext) As MetadataConstant Dim moduleBeingBuilt = DirectCast(context.Module, PEModuleBuilder) Return moduleBeingBuilt.CreateConstant(DirectCast(type, TypeSymbol), value, syntaxNodeOpt:=DirectCast(context.SyntaxNode, VisualBasicSyntaxNode), diagnostics:=context.Diagnostics) End Function Private Function CreateMetadataNamedArgument(name As String, argument As TypedConstant, context As EmitContext) As Cci.IMetadataNamedArgument Dim sym = LookupName(name) Dim value = CreateMetadataExpression(argument, context) Dim type As TypeSymbol Dim fieldSymbol = TryCast(sym, FieldSymbol) If fieldSymbol IsNot Nothing Then type = fieldSymbol.Type Else type = DirectCast(sym, PropertySymbol).Type End If Dim moduleBeingBuilt = DirectCast(context.Module, PEModuleBuilder) Return New MetadataNamedArgument(sym, moduleBeingBuilt.Translate(type, syntaxNodeOpt:=DirectCast(context.SyntaxNode, VisualBasicSyntaxNode), diagnostics:=context.Diagnostics), value) End Function Private Function LookupName(name As String) As Symbol Dim type = AttributeClass Do For Each member In type.GetMembers(name) If member.DeclaredAccessibility = Accessibility.Public Then Return member End If Next type = type.BaseTypeNoUseSiteDiagnostics Loop While type IsNot Nothing Debug.Assert(False, "Name does not match an attribute field or a property. How can that be?") Return ErrorTypeSymbol.UnknownResultType End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Emit Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Partial Friend Class VisualBasicAttributeData Implements Cci.ICustomAttribute Private Function GetArguments1(context As EmitContext) As ImmutableArray(Of Cci.IMetadataExpression) Implements Cci.ICustomAttribute.GetArguments Return CommonConstructorArguments.SelectAsArray(Function(arg) CreateMetadataExpression(arg, context)) End Function Private Function Constructor1(context As EmitContext, reportDiagnostics As Boolean) As Cci.IMethodReference Implements Cci.ICustomAttribute.Constructor If Me.AttributeConstructor.IsDefaultValueTypeConstructor() Then ' Parameter constructors for structs exist in symbol table, but are not emitted. ' Produce an error since we cannot use it (instead of crashing): ' Details: https://github.com/dotnet/roslyn/issues/19394 If reportDiagnostics Then context.Diagnostics.Add(ERRID.ERR_AttributeMustBeClassNotStruct1, If(context.SyntaxNode?.GetLocation(), NoLocation.Singleton), Me.AttributeClass) End If Return Nothing End If Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(context.Module, PEModuleBuilder) Return moduleBeingBuilt.Translate(AttributeConstructor, needDeclaration:=False, syntaxNodeOpt:=DirectCast(context.SyntaxNode, VisualBasicSyntaxNode), diagnostics:=context.Diagnostics) End Function Private Function GetNamedArguments1(context As EmitContext) As ImmutableArray(Of Cci.IMetadataNamedArgument) Implements Cci.ICustomAttribute.GetNamedArguments Return CommonNamedArguments.SelectAsArray(Function(namedArgument) CreateMetadataNamedArgument(namedArgument.Key, namedArgument.Value, context)) End Function Private ReadOnly Property ArgumentCount As Integer Implements Cci.ICustomAttribute.ArgumentCount Get Return CommonConstructorArguments.Length End Get End Property Private ReadOnly Property NamedArgumentCount As UShort Implements Cci.ICustomAttribute.NamedArgumentCount Get Return CType(CommonNamedArguments.Length, UShort) End Get End Property Private Function GetType1(context As EmitContext) As Cci.ITypeReference Implements Cci.ICustomAttribute.GetType Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(context.Module, PEModuleBuilder) Return moduleBeingBuilt.Translate(AttributeClass, syntaxNodeOpt:=DirectCast(context.SyntaxNode, VisualBasicSyntaxNode), diagnostics:=context.Diagnostics) End Function Private ReadOnly Property AllowMultiple1 As Boolean Implements Cci.ICustomAttribute.AllowMultiple Get Return Me.AttributeClass.GetAttributeUsageInfo().AllowMultiple End Get End Property Private Function CreateMetadataExpression(argument As TypedConstant, context As EmitContext) As Cci.IMetadataExpression If argument.IsNull Then Return CreateMetadataConstant(argument.TypeInternal, Nothing, context) End If Select Case argument.Kind Case TypedConstantKind.Array Return CreateMetadataArray(argument, context) Case TypedConstantKind.Type Return CreateType(argument, context) Case Else Return CreateMetadataConstant(argument.TypeInternal, argument.ValueInternal, context) End Select End Function Private Function CreateMetadataArray(argument As TypedConstant, context As EmitContext) As MetadataCreateArray Debug.Assert(Not argument.Values.IsDefault) Dim values = argument.Values Dim moduleBeingBuilt = DirectCast(context.Module, PEModuleBuilder) Dim arrayType = moduleBeingBuilt.Translate(DirectCast(argument.TypeInternal, ArrayTypeSymbol)) If values.Length = 0 Then Return New MetadataCreateArray(arrayType, arrayType.GetElementType(context), ImmutableArray(Of Cci.IMetadataExpression).Empty) End If Dim metadataExprs = New Cci.IMetadataExpression(values.Length - 1) {} For i = 0 To values.Length - 1 metadataExprs(i) = CreateMetadataExpression(values(i), context) Next Return New MetadataCreateArray(arrayType, arrayType.GetElementType(context), metadataExprs.AsImmutableOrNull) End Function Private Function CreateType(argument As TypedConstant, context As EmitContext) As MetadataTypeOf Debug.Assert(argument.ValueInternal IsNot Nothing) Dim moduleBeingBuilt = DirectCast(context.Module, PEModuleBuilder) Dim syntaxNodeOpt = DirectCast(context.SyntaxNode, VisualBasicSyntaxNode) Dim diagnostics = context.Diagnostics Return New MetadataTypeOf(moduleBeingBuilt.Translate(DirectCast(argument.ValueInternal, TypeSymbol), syntaxNodeOpt, diagnostics), moduleBeingBuilt.Translate(DirectCast(argument.TypeInternal, TypeSymbol), syntaxNodeOpt, diagnostics)) End Function Private Function CreateMetadataConstant(type As ITypeSymbolInternal, value As Object, context As EmitContext) As MetadataConstant Dim moduleBeingBuilt = DirectCast(context.Module, PEModuleBuilder) Return moduleBeingBuilt.CreateConstant(DirectCast(type, TypeSymbol), value, syntaxNodeOpt:=DirectCast(context.SyntaxNode, VisualBasicSyntaxNode), diagnostics:=context.Diagnostics) End Function Private Function CreateMetadataNamedArgument(name As String, argument As TypedConstant, context As EmitContext) As Cci.IMetadataNamedArgument Dim sym = LookupName(name) Dim value = CreateMetadataExpression(argument, context) Dim type As TypeSymbol Dim fieldSymbol = TryCast(sym, FieldSymbol) If fieldSymbol IsNot Nothing Then type = fieldSymbol.Type Else type = DirectCast(sym, PropertySymbol).Type End If Dim moduleBeingBuilt = DirectCast(context.Module, PEModuleBuilder) Return New MetadataNamedArgument(sym, moduleBeingBuilt.Translate(type, syntaxNodeOpt:=DirectCast(context.SyntaxNode, VisualBasicSyntaxNode), diagnostics:=context.Diagnostics), value) End Function Private Function LookupName(name As String) As Symbol Dim type = AttributeClass Do For Each member In type.GetMembers(name) If member.DeclaredAccessibility = Accessibility.Public Then Return member End If Next type = type.BaseTypeNoUseSiteDiagnostics Loop While type IsNot Nothing Debug.Assert(False, "Name does not match an attribute field or a property. How can that be?") Return ErrorTypeSymbol.UnknownResultType End Function End Class End Namespace
-1
dotnet/roslyn
55,419
Make vsix's compatible with vs 2022
Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
dibarbet
2021-08-04T23:36:41Z
2021-08-06T17:54:08Z
082df2aaf6a73277fc27f9d7a5a8d18ee45d7f8b
e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028
Make vsix's compatible with vs 2022. Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
./src/VisualStudio/Core/Impl/SolutionExplorer/AnalyzersFolderItem/AnalyzersFolderItem.BrowseObject.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.ComponentModel; namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer { internal partial class AnalyzersFolderItem { internal class BrowseObject : LocalizableProperties { private readonly AnalyzersFolderItem _analyzersFolderItem; public BrowseObject(AnalyzersFolderItem analyzersFolderItem) { _analyzersFolderItem = analyzersFolderItem; } public override string GetClassName() { return SolutionExplorerShim.Folder_Properties; } public override string GetComponentName() { return _analyzersFolderItem.Text; } [Browsable(false)] public AnalyzersFolderItem Folder { get { return _analyzersFolderItem; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.ComponentModel; namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer { internal partial class AnalyzersFolderItem { internal class BrowseObject : LocalizableProperties { private readonly AnalyzersFolderItem _analyzersFolderItem; public BrowseObject(AnalyzersFolderItem analyzersFolderItem) { _analyzersFolderItem = analyzersFolderItem; } public override string GetClassName() { return SolutionExplorerShim.Folder_Properties; } public override string GetComponentName() { return _analyzersFolderItem.Text; } [Browsable(false)] public AnalyzersFolderItem Folder { get { return _analyzersFolderItem; } } } } }
-1
dotnet/roslyn
55,419
Make vsix's compatible with vs 2022
Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
dibarbet
2021-08-04T23:36:41Z
2021-08-06T17:54:08Z
082df2aaf6a73277fc27f9d7a5a8d18ee45d7f8b
e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028
Make vsix's compatible with vs 2022. Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
./src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.es.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="es" original="../EditorFeaturesWpfResources.resx"> <body> <trans-unit id="Building_Project"> <source>Building Project</source> <target state="translated">Generando proyecto</target> <note /> </trans-unit> <trans-unit id="Copying_selection_to_Interactive_Window"> <source>Copying selection to Interactive Window.</source> <target state="translated">Copiando selección en ventana interactiva.</target> <note /> </trans-unit> <trans-unit id="Error_performing_rename_0"> <source>Error performing rename: '{0}'</source> <target state="translated">Error al realizar el cambio de nombre: "{0}"</target> <note /> </trans-unit> <trans-unit id="Executing_selection_in_Interactive_Window"> <source>Executing selection in Interactive Window.</source> <target state="translated">Ejecutando selección en ventana interactiva.</target> <note /> </trans-unit> <trans-unit id="Interactive_host_process_platform"> <source>Interactive host process platform</source> <target state="translated">Plataforma de proceso de host interactiva</target> <note /> </trans-unit> <trans-unit id="Print_a_list_of_referenced_assemblies"> <source>Print a list of referenced assemblies.</source> <target state="translated">Imprima una lista de ensamblados de referencia.</target> <note /> </trans-unit> <trans-unit id="Regex_Comment"> <source>Regex - Comment</source> <target state="translated">Regex - comentario</target> <note /> </trans-unit> <trans-unit id="Regex_Character_Class"> <source>Regex - Character Class</source> <target state="translated">Regex - clase de caracteres</target> <note /> </trans-unit> <trans-unit id="Regex_Alternation"> <source>Regex - Alternation</source> <target state="translated">Regex - alternancia</target> <note /> </trans-unit> <trans-unit id="Regex_Anchor"> <source>Regex - Anchor</source> <target state="translated">Regex - ancla</target> <note /> </trans-unit> <trans-unit id="Regex_Quantifier"> <source>Regex - Quantifier</source> <target state="translated">Regex - cuantificador</target> <note /> </trans-unit> <trans-unit id="Regex_SelfEscapedCharacter"> <source>Regex - Self Escaped Character</source> <target state="translated">Regex - carácter de autoescape</target> <note /> </trans-unit> <trans-unit id="Regex_Grouping"> <source>Regex - Grouping</source> <target state="translated">Regex - agrupación</target> <note /> </trans-unit> <trans-unit id="Regex_Text"> <source>Regex - Text</source> <target state="translated">Regex - texto</target> <note /> </trans-unit> <trans-unit id="Regex_OtherEscape"> <source>Regex - Other Escape</source> <target state="translated">Regex - otro Escape</target> <note /> </trans-unit> <trans-unit id="Reset_the_execution_environment_to_the_initial_state_keep_history"> <source>Reset the execution environment to the initial state, keep history.</source> <target state="translated">Restablecer el entorno de ejecución al estado inicial, conservar el historial.</target> <note /> </trans-unit> <trans-unit id="Reset_to_a_clean_environment_only_mscorlib_referenced_do_not_run_initialization_script"> <source>Reset to a clean environment (only mscorlib referenced), do not run initialization script.</source> <target state="translated">Restablecer a un entorno limpio (referencia exclusiva a mscorlib), no ejecutar el script de inicialización.</target> <note /> </trans-unit> <trans-unit id="Resetting_Interactive"> <source>Resetting Interactive</source> <target state="translated">Restableciendo interactivo</target> <note /> </trans-unit> <trans-unit id="Resetting_execution_engine"> <source>Resetting execution engine.</source> <target state="translated">Restableciendo el motor de ejecución.</target> <note /> </trans-unit> <trans-unit id="The_CurrentWindow_property_may_only_be_assigned_once"> <source>The CurrentWindow property may only be assigned once.</source> <target state="translated">La propiedad CurrentWindow solo se puede asignar una vez.</target> <note /> </trans-unit> <trans-unit id="The_references_command_is_not_supported_in_this_Interactive_Window_implementation"> <source>The references command is not supported in this Interactive Window implementation.</source> <target state="translated">No se admite el comando de referencias en esta implementación de ventana interactiva.</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="es" original="../EditorFeaturesWpfResources.resx"> <body> <trans-unit id="Building_Project"> <source>Building Project</source> <target state="translated">Generando proyecto</target> <note /> </trans-unit> <trans-unit id="Copying_selection_to_Interactive_Window"> <source>Copying selection to Interactive Window.</source> <target state="translated">Copiando selección en ventana interactiva.</target> <note /> </trans-unit> <trans-unit id="Error_performing_rename_0"> <source>Error performing rename: '{0}'</source> <target state="translated">Error al realizar el cambio de nombre: "{0}"</target> <note /> </trans-unit> <trans-unit id="Executing_selection_in_Interactive_Window"> <source>Executing selection in Interactive Window.</source> <target state="translated">Ejecutando selección en ventana interactiva.</target> <note /> </trans-unit> <trans-unit id="Interactive_host_process_platform"> <source>Interactive host process platform</source> <target state="translated">Plataforma de proceso de host interactiva</target> <note /> </trans-unit> <trans-unit id="Print_a_list_of_referenced_assemblies"> <source>Print a list of referenced assemblies.</source> <target state="translated">Imprima una lista de ensamblados de referencia.</target> <note /> </trans-unit> <trans-unit id="Regex_Comment"> <source>Regex - Comment</source> <target state="translated">Regex - comentario</target> <note /> </trans-unit> <trans-unit id="Regex_Character_Class"> <source>Regex - Character Class</source> <target state="translated">Regex - clase de caracteres</target> <note /> </trans-unit> <trans-unit id="Regex_Alternation"> <source>Regex - Alternation</source> <target state="translated">Regex - alternancia</target> <note /> </trans-unit> <trans-unit id="Regex_Anchor"> <source>Regex - Anchor</source> <target state="translated">Regex - ancla</target> <note /> </trans-unit> <trans-unit id="Regex_Quantifier"> <source>Regex - Quantifier</source> <target state="translated">Regex - cuantificador</target> <note /> </trans-unit> <trans-unit id="Regex_SelfEscapedCharacter"> <source>Regex - Self Escaped Character</source> <target state="translated">Regex - carácter de autoescape</target> <note /> </trans-unit> <trans-unit id="Regex_Grouping"> <source>Regex - Grouping</source> <target state="translated">Regex - agrupación</target> <note /> </trans-unit> <trans-unit id="Regex_Text"> <source>Regex - Text</source> <target state="translated">Regex - texto</target> <note /> </trans-unit> <trans-unit id="Regex_OtherEscape"> <source>Regex - Other Escape</source> <target state="translated">Regex - otro Escape</target> <note /> </trans-unit> <trans-unit id="Reset_the_execution_environment_to_the_initial_state_keep_history"> <source>Reset the execution environment to the initial state, keep history.</source> <target state="translated">Restablecer el entorno de ejecución al estado inicial, conservar el historial.</target> <note /> </trans-unit> <trans-unit id="Reset_to_a_clean_environment_only_mscorlib_referenced_do_not_run_initialization_script"> <source>Reset to a clean environment (only mscorlib referenced), do not run initialization script.</source> <target state="translated">Restablecer a un entorno limpio (referencia exclusiva a mscorlib), no ejecutar el script de inicialización.</target> <note /> </trans-unit> <trans-unit id="Resetting_Interactive"> <source>Resetting Interactive</source> <target state="translated">Restableciendo interactivo</target> <note /> </trans-unit> <trans-unit id="Resetting_execution_engine"> <source>Resetting execution engine.</source> <target state="translated">Restableciendo el motor de ejecución.</target> <note /> </trans-unit> <trans-unit id="The_CurrentWindow_property_may_only_be_assigned_once"> <source>The CurrentWindow property may only be assigned once.</source> <target state="translated">La propiedad CurrentWindow solo se puede asignar una vez.</target> <note /> </trans-unit> <trans-unit id="The_references_command_is_not_supported_in_this_Interactive_Window_implementation"> <source>The references command is not supported in this Interactive Window implementation.</source> <target state="translated">No se admite el comando de referencias en esta implementación de ventana interactiva.</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,419
Make vsix's compatible with vs 2022
Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
dibarbet
2021-08-04T23:36:41Z
2021-08-06T17:54:08Z
082df2aaf6a73277fc27f9d7a5a8d18ee45d7f8b
e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028
Make vsix's compatible with vs 2022. Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
./src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_Call.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Diagnostics Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend NotInheritable Class LocalRewriter Public Overrides Function VisitCall(node As BoundCall) As BoundNode Debug.Assert(Not node.IsConstant, "Constant calls should become literals by now") Dim receiver As BoundExpression = node.ReceiverOpt Dim method As MethodSymbol = node.Method Dim arguments As ImmutableArray(Of BoundExpression) = node.Arguments ' Replace a call to AscW(<non constant char>) with a conversion, this makes sure we don't have a recursion inside AscW(Char). If method Is Compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Strings__AscWCharInt32) Then Return New BoundConversion(node.Syntax, VisitExpressionNode(arguments(0)), ConversionKind.WideningNumeric, checked:=False, explicitCastInCode:=True, type:=node.Type) End If ' Code below is for remapping of versioned functions. ' ' Code compiled with VS7.1 or earlier must run on VS8.0 with no behavior changes. ' However, since VS8.0 introduces several new features which change the behavior of ' Public functions, we introduce the new behavior in a new function and map references ' to the old function onto the new function. In this way, old code continues to run and ' new code gets the new behavior, but the Public function doesn't change at all, from the ' user's point of view. ' Example: ' ' Given: ' 1. User code snippet: "If IsNumeric(something) Then ..." ' 2. Public Function IsNumeric(o), has VS7.1 behavior. ' 3. Public Function Versioned.IsNumeric(o), has VS8.0 behavior. ' ' When compiled in VS7.1, the compiler binds to IsNumeric(o). ' When compiled in VS8.0, the compiler first binds to IsNumeric(o) and then remaps ' this binding to Versioned.IsNumeric(o) in the code generator so that the VS8.0 ' behavior is selected. ' Dim remappedMethodId As WellKnownMember = WellKnownMember.Count If method Is Compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Interaction__CallByName) Then remappedMethodId = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Versioned__CallByName ElseIf method.ContainingSymbol Is Compilation.GetWellKnownType(WellKnownType.Microsoft_VisualBasic_Information) Then If method Is Compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Information__IsNumeric) Then remappedMethodId = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Versioned__IsNumeric ElseIf method Is Compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Information__SystemTypeName) Then remappedMethodId = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Versioned__SystemTypeName ElseIf method Is Compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Information__TypeName) Then remappedMethodId = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Versioned__TypeName ElseIf method Is Compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Information__VbTypeName) Then remappedMethodId = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Versioned__VbTypeName End If End If If remappedMethodId <> WellKnownMember.Count Then Dim remappedMethod = DirectCast(Compilation.GetWellKnownTypeMember(remappedMethodId), MethodSymbol) If remappedMethod IsNot Nothing AndAlso Not ReportMissingOrBadRuntimeHelper(node, remappedMethodId, remappedMethod) Then method = remappedMethod End If End If UpdateMethodAndArgumentsIfReducedFromMethod(method, receiver, arguments) Dim temporaries As ImmutableArray(Of SynthesizedLocal) = Nothing Dim copyBack As ImmutableArray(Of BoundExpression) = Nothing Dim suppressObjectClone As Boolean = node.SuppressObjectClone OrElse method Is Compilation.GetWellKnownTypeMember( WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__GetObjectValueObject) receiver = VisitExpressionNode(receiver) node = node.Update(method, Nothing, receiver, RewriteCallArguments(arguments, method.Parameters, temporaries, copyBack, suppressObjectClone), node.DefaultArguments, Nothing, isLValue:=node.IsLValue, suppressObjectClone:=True, type:=node.Type) If Not copyBack.IsDefault Then Return GenerateSequenceValueSideEffects(_currentMethodOrLambda, node, StaticCast(Of LocalSymbol).From(temporaries), copyBack) End If If Not temporaries.IsDefault Then If method.IsSub Then Return New BoundSequence(node.Syntax, StaticCast(Of LocalSymbol).From(temporaries), ImmutableArray.Create(Of BoundExpression)(node), Nothing, node.Type) Else Return New BoundSequence(node.Syntax, StaticCast(Of LocalSymbol).From(temporaries), ImmutableArray(Of BoundExpression).Empty, node, node.Type) End If End If Return node End Function Private Shared Sub UpdateMethodAndArgumentsIfReducedFromMethod( ByRef method As MethodSymbol, ByRef receiver As BoundExpression, ByRef arguments As ImmutableArray(Of BoundExpression)) If receiver Is Nothing Then Return End If Dim reducedFrom As MethodSymbol = method.CallsiteReducedFromMethod If reducedFrom Is Nothing Then Return End If ' This is an extension method call If arguments.IsEmpty Then arguments = ImmutableArray.Create(Of BoundExpression)(receiver) Else Dim array(arguments.Length) As BoundExpression array(0) = receiver arguments.CopyTo(array, 1) arguments = array.AsImmutableOrNull() End If receiver = Nothing method = reducedFrom End Sub Public Overrides Function VisitByRefArgumentWithCopyBack(node As BoundByRefArgumentWithCopyBack) As BoundNode Throw ExceptionUtilities.Unreachable End Function Private Function RewriteCallArguments( arguments As ImmutableArray(Of BoundExpression), parameters As ImmutableArray(Of ParameterSymbol), <Out()> ByRef temporaries As ImmutableArray(Of SynthesizedLocal), <Out()> ByRef copyBack As ImmutableArray(Of BoundExpression), suppressObjectClone As Boolean ) As ImmutableArray(Of BoundExpression) temporaries = Nothing copyBack = Nothing If arguments.IsEmpty Then Return arguments End If Dim tempsArray As ArrayBuilder(Of SynthesizedLocal) = Nothing Dim copyBackArray As ArrayBuilder(Of BoundExpression) = Nothing Dim rewrittenArgs = ArrayBuilder(Of BoundExpression).GetInstance Dim changed As Boolean = False Dim paramIdx = 0 For Each argument In arguments Dim rewritten As BoundExpression If argument.Kind = BoundKind.ByRefArgumentWithCopyBack Then rewritten = RewriteByRefArgumentWithCopyBack(DirectCast(argument, BoundByRefArgumentWithCopyBack), tempsArray, copyBackArray) Else rewritten = VisitExpressionNode(argument) If parameters(paramIdx).IsByRef AndAlso Not argument.IsLValue AndAlso Not _inExpressionLambda Then rewritten = PassArgAsTempClone(argument, rewritten, tempsArray) End If End If If Not suppressObjectClone AndAlso (Not parameters(paramIdx).IsByRef OrElse Not rewritten.IsLValue) Then rewritten = GenerateObjectCloneIfNeeded(argument, rewritten) End If If rewritten IsNot argument Then changed = True End If rewrittenArgs.Add(rewritten) paramIdx += 1 Next Debug.Assert(temporaries.IsDefault OrElse changed) If changed Then arguments = rewrittenArgs.ToImmutable() End If rewrittenArgs.Free() If tempsArray IsNot Nothing Then temporaries = tempsArray.ToImmutableAndFree() End If If copyBackArray IsNot Nothing Then ' It might feel strange, but Dev11 evaluates copy-back assignments in reverse order (from last argument to the first), ' which is observable. Doing the same thing. copyBackArray.ReverseContents() copyBack = copyBackArray.ToImmutableAndFree() End If Return arguments End Function Private Function PassArgAsTempClone( argument As BoundExpression, rewrittenArgument As BoundExpression, ByRef tempsArray As ArrayBuilder(Of SynthesizedLocal) ) As BoundExpression ' Need to allocate a temp of the target type, ' init it with argument's value, ' pass it ByRef If tempsArray Is Nothing Then tempsArray = ArrayBuilder(Of SynthesizedLocal).GetInstance() End If Dim temp = New SynthesizedLocal(Me._currentMethodOrLambda, rewrittenArgument.Type, SynthesizedLocalKind.LoweringTemp) tempsArray.Add(temp) Dim boundTemp = New BoundLocal(rewrittenArgument.Syntax, temp, temp.Type) Dim storeVal As BoundExpression = New BoundAssignmentOperator(rewrittenArgument.Syntax, boundTemp, GenerateObjectCloneIfNeeded(argument, rewrittenArgument), True, rewrittenArgument.Type) Return New BoundSequence(rewrittenArgument.Syntax, ImmutableArray(Of LocalSymbol).Empty, ImmutableArray.Create(storeVal), boundTemp, rewrittenArgument.Type) End Function Private Function RewriteByRefArgumentWithCopyBack( argument As BoundByRefArgumentWithCopyBack, ByRef tempsArray As ArrayBuilder(Of SynthesizedLocal), ByRef copyBackArray As ArrayBuilder(Of BoundExpression) ) As BoundExpression ' Need to allocate a temp of the target type, ' init it with argument's value, ' pass it ByRef, ' copy value back after the call. Dim originalArgument As BoundExpression = argument.OriginalArgument If originalArgument.IsPropertyOrXmlPropertyAccess Then Debug.Assert(originalArgument.GetAccessKind() = If( originalArgument.IsPropertyReturnsByRef(), PropertyAccessKind.Get, PropertyAccessKind.Get Or PropertyAccessKind.Set)) originalArgument = originalArgument.SetAccessKind(PropertyAccessKind.Unknown) ElseIf originalArgument.IsLateBound() Then Debug.Assert(originalArgument.GetLateBoundAccessKind() = (LateBoundAccessKind.Get Or LateBoundAccessKind.Set)) originalArgument = originalArgument.SetLateBoundAccessKind(LateBoundAccessKind.Unknown) End If If _inExpressionLambda Then If originalArgument.IsPropertyOrXmlPropertyAccess Then Debug.Assert(originalArgument.GetAccessKind() = PropertyAccessKind.Unknown) originalArgument = originalArgument.SetAccessKind(PropertyAccessKind.Get) ElseIf originalArgument.IsLateBound() Then Debug.Assert(originalArgument.GetLateBoundAccessKind() = LateBoundAccessKind.Unknown) originalArgument = originalArgument.SetLateBoundAccessKind(LateBoundAccessKind.Get) End If If originalArgument.IsLValue Then originalArgument = originalArgument.MakeRValue End If AddPlaceholderReplacement(argument.InPlaceholder, VisitExpressionNode(originalArgument)) Dim rewrittenArgumentInConversion As BoundExpression = VisitExpression(argument.InConversion) RemovePlaceholderReplacement(argument.InPlaceholder) Return rewrittenArgumentInConversion End If If tempsArray Is Nothing Then tempsArray = ArrayBuilder(Of SynthesizedLocal).GetInstance() End If If copyBackArray Is Nothing Then copyBackArray = ArrayBuilder(Of BoundExpression).GetInstance() End If Dim firstUse As BoundExpression Dim secondUse As BoundExpression Dim useTwice As UseTwiceRewriter.Result = UseTwiceRewriter.UseTwice(Me._currentMethodOrLambda, originalArgument, tempsArray) If originalArgument.IsPropertyOrXmlPropertyAccess Then firstUse = useTwice.First.SetAccessKind(PropertyAccessKind.Get).MakeRValue() secondUse = useTwice.Second.SetAccessKind(If(originalArgument.IsPropertyReturnsByRef(), PropertyAccessKind.Get, PropertyAccessKind.Set)) ElseIf originalArgument.IsLateBound() Then firstUse = useTwice.First.SetLateBoundAccessKind(LateBoundAccessKind.Get) secondUse = useTwice.Second.SetLateBoundAccessKind(LateBoundAccessKind.Set) Else firstUse = useTwice.First.MakeRValue() secondUse = useTwice.Second Debug.Assert(secondUse.IsLValue) End If AddPlaceholderReplacement(argument.InPlaceholder, VisitExpressionNode(firstUse)) Dim inputValue As BoundExpression = VisitAndGenerateObjectCloneIfNeeded(argument.InConversion) RemovePlaceholderReplacement(argument.InPlaceholder) Dim temp = New SynthesizedLocal(Me._currentMethodOrLambda, argument.Type, SynthesizedLocalKind.LoweringTemp) tempsArray.Add(temp) Dim boundTemp = New BoundLocal(argument.Syntax, temp, temp.Type) Dim storeVal As BoundExpression = New BoundAssignmentOperator(argument.Syntax, boundTemp, inputValue, True, argument.Type) AddPlaceholderReplacement(argument.OutPlaceholder, boundTemp.MakeRValue()) Dim copyBack As BoundExpression If Not originalArgument.IsLateBound() Then copyBack = DirectCast( VisitAssignmentOperator(New BoundAssignmentOperator(argument.Syntax, secondUse, argument.OutConversion, False)), BoundExpression) RemovePlaceholderReplacement(argument.OutPlaceholder) Else Dim copyBackValue As BoundExpression = VisitExpressionNode(argument.OutConversion) RemovePlaceholderReplacement(argument.OutPlaceholder) If secondUse.Kind = BoundKind.LateMemberAccess Then ' Method(ref objExpr.goo) copyBack = LateSet(secondUse.Syntax, DirectCast(MyBase.VisitLateMemberAccess(DirectCast(secondUse, BoundLateMemberAccess)), BoundLateMemberAccess), copyBackValue, Nothing, Nothing, isCopyBack:=True) Else Dim invocation = DirectCast(secondUse, BoundLateInvocation) If invocation.Member.Kind = BoundKind.LateMemberAccess Then ' Method(ref objExpr.goo(args)) copyBack = LateSet(invocation.Syntax, DirectCast(MyBase.VisitLateMemberAccess(DirectCast(invocation.Member, BoundLateMemberAccess)), BoundLateMemberAccess), copyBackValue, VisitList(invocation.ArgumentsOpt), invocation.ArgumentNamesOpt, isCopyBack:=True) Else ' Method(ref objExpr(args)) invocation = invocation.Update(VisitExpressionNode(invocation.Member), VisitList(invocation.ArgumentsOpt), invocation.ArgumentNamesOpt, invocation.AccessKind, invocation.MethodOrPropertyGroupOpt, invocation.Type) copyBack = LateIndexSet(invocation.Syntax, invocation, copyBackValue, isCopyBack:=True) End If End If End If copyBackArray.Add(copyBack) Return New BoundSequence(argument.Syntax, ImmutableArray(Of LocalSymbol).Empty, ImmutableArray.Create(storeVal), boundTemp, argument.Type) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Diagnostics Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend NotInheritable Class LocalRewriter Public Overrides Function VisitCall(node As BoundCall) As BoundNode Debug.Assert(Not node.IsConstant, "Constant calls should become literals by now") Dim receiver As BoundExpression = node.ReceiverOpt Dim method As MethodSymbol = node.Method Dim arguments As ImmutableArray(Of BoundExpression) = node.Arguments ' Replace a call to AscW(<non constant char>) with a conversion, this makes sure we don't have a recursion inside AscW(Char). If method Is Compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Strings__AscWCharInt32) Then Return New BoundConversion(node.Syntax, VisitExpressionNode(arguments(0)), ConversionKind.WideningNumeric, checked:=False, explicitCastInCode:=True, type:=node.Type) End If ' Code below is for remapping of versioned functions. ' ' Code compiled with VS7.1 or earlier must run on VS8.0 with no behavior changes. ' However, since VS8.0 introduces several new features which change the behavior of ' Public functions, we introduce the new behavior in a new function and map references ' to the old function onto the new function. In this way, old code continues to run and ' new code gets the new behavior, but the Public function doesn't change at all, from the ' user's point of view. ' Example: ' ' Given: ' 1. User code snippet: "If IsNumeric(something) Then ..." ' 2. Public Function IsNumeric(o), has VS7.1 behavior. ' 3. Public Function Versioned.IsNumeric(o), has VS8.0 behavior. ' ' When compiled in VS7.1, the compiler binds to IsNumeric(o). ' When compiled in VS8.0, the compiler first binds to IsNumeric(o) and then remaps ' this binding to Versioned.IsNumeric(o) in the code generator so that the VS8.0 ' behavior is selected. ' Dim remappedMethodId As WellKnownMember = WellKnownMember.Count If method Is Compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Interaction__CallByName) Then remappedMethodId = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Versioned__CallByName ElseIf method.ContainingSymbol Is Compilation.GetWellKnownType(WellKnownType.Microsoft_VisualBasic_Information) Then If method Is Compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Information__IsNumeric) Then remappedMethodId = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Versioned__IsNumeric ElseIf method Is Compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Information__SystemTypeName) Then remappedMethodId = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Versioned__SystemTypeName ElseIf method Is Compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Information__TypeName) Then remappedMethodId = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Versioned__TypeName ElseIf method Is Compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Information__VbTypeName) Then remappedMethodId = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Versioned__VbTypeName End If End If If remappedMethodId <> WellKnownMember.Count Then Dim remappedMethod = DirectCast(Compilation.GetWellKnownTypeMember(remappedMethodId), MethodSymbol) If remappedMethod IsNot Nothing AndAlso Not ReportMissingOrBadRuntimeHelper(node, remappedMethodId, remappedMethod) Then method = remappedMethod End If End If UpdateMethodAndArgumentsIfReducedFromMethod(method, receiver, arguments) Dim temporaries As ImmutableArray(Of SynthesizedLocal) = Nothing Dim copyBack As ImmutableArray(Of BoundExpression) = Nothing Dim suppressObjectClone As Boolean = node.SuppressObjectClone OrElse method Is Compilation.GetWellKnownTypeMember( WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__GetObjectValueObject) receiver = VisitExpressionNode(receiver) node = node.Update(method, Nothing, receiver, RewriteCallArguments(arguments, method.Parameters, temporaries, copyBack, suppressObjectClone), node.DefaultArguments, Nothing, isLValue:=node.IsLValue, suppressObjectClone:=True, type:=node.Type) If Not copyBack.IsDefault Then Return GenerateSequenceValueSideEffects(_currentMethodOrLambda, node, StaticCast(Of LocalSymbol).From(temporaries), copyBack) End If If Not temporaries.IsDefault Then If method.IsSub Then Return New BoundSequence(node.Syntax, StaticCast(Of LocalSymbol).From(temporaries), ImmutableArray.Create(Of BoundExpression)(node), Nothing, node.Type) Else Return New BoundSequence(node.Syntax, StaticCast(Of LocalSymbol).From(temporaries), ImmutableArray(Of BoundExpression).Empty, node, node.Type) End If End If Return node End Function Private Shared Sub UpdateMethodAndArgumentsIfReducedFromMethod( ByRef method As MethodSymbol, ByRef receiver As BoundExpression, ByRef arguments As ImmutableArray(Of BoundExpression)) If receiver Is Nothing Then Return End If Dim reducedFrom As MethodSymbol = method.CallsiteReducedFromMethod If reducedFrom Is Nothing Then Return End If ' This is an extension method call If arguments.IsEmpty Then arguments = ImmutableArray.Create(Of BoundExpression)(receiver) Else Dim array(arguments.Length) As BoundExpression array(0) = receiver arguments.CopyTo(array, 1) arguments = array.AsImmutableOrNull() End If receiver = Nothing method = reducedFrom End Sub Public Overrides Function VisitByRefArgumentWithCopyBack(node As BoundByRefArgumentWithCopyBack) As BoundNode Throw ExceptionUtilities.Unreachable End Function Private Function RewriteCallArguments( arguments As ImmutableArray(Of BoundExpression), parameters As ImmutableArray(Of ParameterSymbol), <Out()> ByRef temporaries As ImmutableArray(Of SynthesizedLocal), <Out()> ByRef copyBack As ImmutableArray(Of BoundExpression), suppressObjectClone As Boolean ) As ImmutableArray(Of BoundExpression) temporaries = Nothing copyBack = Nothing If arguments.IsEmpty Then Return arguments End If Dim tempsArray As ArrayBuilder(Of SynthesizedLocal) = Nothing Dim copyBackArray As ArrayBuilder(Of BoundExpression) = Nothing Dim rewrittenArgs = ArrayBuilder(Of BoundExpression).GetInstance Dim changed As Boolean = False Dim paramIdx = 0 For Each argument In arguments Dim rewritten As BoundExpression If argument.Kind = BoundKind.ByRefArgumentWithCopyBack Then rewritten = RewriteByRefArgumentWithCopyBack(DirectCast(argument, BoundByRefArgumentWithCopyBack), tempsArray, copyBackArray) Else rewritten = VisitExpressionNode(argument) If parameters(paramIdx).IsByRef AndAlso Not argument.IsLValue AndAlso Not _inExpressionLambda Then rewritten = PassArgAsTempClone(argument, rewritten, tempsArray) End If End If If Not suppressObjectClone AndAlso (Not parameters(paramIdx).IsByRef OrElse Not rewritten.IsLValue) Then rewritten = GenerateObjectCloneIfNeeded(argument, rewritten) End If If rewritten IsNot argument Then changed = True End If rewrittenArgs.Add(rewritten) paramIdx += 1 Next Debug.Assert(temporaries.IsDefault OrElse changed) If changed Then arguments = rewrittenArgs.ToImmutable() End If rewrittenArgs.Free() If tempsArray IsNot Nothing Then temporaries = tempsArray.ToImmutableAndFree() End If If copyBackArray IsNot Nothing Then ' It might feel strange, but Dev11 evaluates copy-back assignments in reverse order (from last argument to the first), ' which is observable. Doing the same thing. copyBackArray.ReverseContents() copyBack = copyBackArray.ToImmutableAndFree() End If Return arguments End Function Private Function PassArgAsTempClone( argument As BoundExpression, rewrittenArgument As BoundExpression, ByRef tempsArray As ArrayBuilder(Of SynthesizedLocal) ) As BoundExpression ' Need to allocate a temp of the target type, ' init it with argument's value, ' pass it ByRef If tempsArray Is Nothing Then tempsArray = ArrayBuilder(Of SynthesizedLocal).GetInstance() End If Dim temp = New SynthesizedLocal(Me._currentMethodOrLambda, rewrittenArgument.Type, SynthesizedLocalKind.LoweringTemp) tempsArray.Add(temp) Dim boundTemp = New BoundLocal(rewrittenArgument.Syntax, temp, temp.Type) Dim storeVal As BoundExpression = New BoundAssignmentOperator(rewrittenArgument.Syntax, boundTemp, GenerateObjectCloneIfNeeded(argument, rewrittenArgument), True, rewrittenArgument.Type) Return New BoundSequence(rewrittenArgument.Syntax, ImmutableArray(Of LocalSymbol).Empty, ImmutableArray.Create(storeVal), boundTemp, rewrittenArgument.Type) End Function Private Function RewriteByRefArgumentWithCopyBack( argument As BoundByRefArgumentWithCopyBack, ByRef tempsArray As ArrayBuilder(Of SynthesizedLocal), ByRef copyBackArray As ArrayBuilder(Of BoundExpression) ) As BoundExpression ' Need to allocate a temp of the target type, ' init it with argument's value, ' pass it ByRef, ' copy value back after the call. Dim originalArgument As BoundExpression = argument.OriginalArgument If originalArgument.IsPropertyOrXmlPropertyAccess Then Debug.Assert(originalArgument.GetAccessKind() = If( originalArgument.IsPropertyReturnsByRef(), PropertyAccessKind.Get, PropertyAccessKind.Get Or PropertyAccessKind.Set)) originalArgument = originalArgument.SetAccessKind(PropertyAccessKind.Unknown) ElseIf originalArgument.IsLateBound() Then Debug.Assert(originalArgument.GetLateBoundAccessKind() = (LateBoundAccessKind.Get Or LateBoundAccessKind.Set)) originalArgument = originalArgument.SetLateBoundAccessKind(LateBoundAccessKind.Unknown) End If If _inExpressionLambda Then If originalArgument.IsPropertyOrXmlPropertyAccess Then Debug.Assert(originalArgument.GetAccessKind() = PropertyAccessKind.Unknown) originalArgument = originalArgument.SetAccessKind(PropertyAccessKind.Get) ElseIf originalArgument.IsLateBound() Then Debug.Assert(originalArgument.GetLateBoundAccessKind() = LateBoundAccessKind.Unknown) originalArgument = originalArgument.SetLateBoundAccessKind(LateBoundAccessKind.Get) End If If originalArgument.IsLValue Then originalArgument = originalArgument.MakeRValue End If AddPlaceholderReplacement(argument.InPlaceholder, VisitExpressionNode(originalArgument)) Dim rewrittenArgumentInConversion As BoundExpression = VisitExpression(argument.InConversion) RemovePlaceholderReplacement(argument.InPlaceholder) Return rewrittenArgumentInConversion End If If tempsArray Is Nothing Then tempsArray = ArrayBuilder(Of SynthesizedLocal).GetInstance() End If If copyBackArray Is Nothing Then copyBackArray = ArrayBuilder(Of BoundExpression).GetInstance() End If Dim firstUse As BoundExpression Dim secondUse As BoundExpression Dim useTwice As UseTwiceRewriter.Result = UseTwiceRewriter.UseTwice(Me._currentMethodOrLambda, originalArgument, tempsArray) If originalArgument.IsPropertyOrXmlPropertyAccess Then firstUse = useTwice.First.SetAccessKind(PropertyAccessKind.Get).MakeRValue() secondUse = useTwice.Second.SetAccessKind(If(originalArgument.IsPropertyReturnsByRef(), PropertyAccessKind.Get, PropertyAccessKind.Set)) ElseIf originalArgument.IsLateBound() Then firstUse = useTwice.First.SetLateBoundAccessKind(LateBoundAccessKind.Get) secondUse = useTwice.Second.SetLateBoundAccessKind(LateBoundAccessKind.Set) Else firstUse = useTwice.First.MakeRValue() secondUse = useTwice.Second Debug.Assert(secondUse.IsLValue) End If AddPlaceholderReplacement(argument.InPlaceholder, VisitExpressionNode(firstUse)) Dim inputValue As BoundExpression = VisitAndGenerateObjectCloneIfNeeded(argument.InConversion) RemovePlaceholderReplacement(argument.InPlaceholder) Dim temp = New SynthesizedLocal(Me._currentMethodOrLambda, argument.Type, SynthesizedLocalKind.LoweringTemp) tempsArray.Add(temp) Dim boundTemp = New BoundLocal(argument.Syntax, temp, temp.Type) Dim storeVal As BoundExpression = New BoundAssignmentOperator(argument.Syntax, boundTemp, inputValue, True, argument.Type) AddPlaceholderReplacement(argument.OutPlaceholder, boundTemp.MakeRValue()) Dim copyBack As BoundExpression If Not originalArgument.IsLateBound() Then copyBack = DirectCast( VisitAssignmentOperator(New BoundAssignmentOperator(argument.Syntax, secondUse, argument.OutConversion, False)), BoundExpression) RemovePlaceholderReplacement(argument.OutPlaceholder) Else Dim copyBackValue As BoundExpression = VisitExpressionNode(argument.OutConversion) RemovePlaceholderReplacement(argument.OutPlaceholder) If secondUse.Kind = BoundKind.LateMemberAccess Then ' Method(ref objExpr.goo) copyBack = LateSet(secondUse.Syntax, DirectCast(MyBase.VisitLateMemberAccess(DirectCast(secondUse, BoundLateMemberAccess)), BoundLateMemberAccess), copyBackValue, Nothing, Nothing, isCopyBack:=True) Else Dim invocation = DirectCast(secondUse, BoundLateInvocation) If invocation.Member.Kind = BoundKind.LateMemberAccess Then ' Method(ref objExpr.goo(args)) copyBack = LateSet(invocation.Syntax, DirectCast(MyBase.VisitLateMemberAccess(DirectCast(invocation.Member, BoundLateMemberAccess)), BoundLateMemberAccess), copyBackValue, VisitList(invocation.ArgumentsOpt), invocation.ArgumentNamesOpt, isCopyBack:=True) Else ' Method(ref objExpr(args)) invocation = invocation.Update(VisitExpressionNode(invocation.Member), VisitList(invocation.ArgumentsOpt), invocation.ArgumentNamesOpt, invocation.AccessKind, invocation.MethodOrPropertyGroupOpt, invocation.Type) copyBack = LateIndexSet(invocation.Syntax, invocation, copyBackValue, isCopyBack:=True) End If End If End If copyBackArray.Add(copyBack) Return New BoundSequence(argument.Syntax, ImmutableArray(Of LocalSymbol).Empty, ImmutableArray.Create(storeVal), boundTemp, argument.Type) End Function End Class End Namespace
-1
dotnet/roslyn
55,419
Make vsix's compatible with vs 2022
Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
dibarbet
2021-08-04T23:36:41Z
2021-08-06T17:54:08Z
082df2aaf6a73277fc27f9d7a5a8d18ee45d7f8b
e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028
Make vsix's compatible with vs 2022. Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
./scripts/check-for-loc-changes.cmd
@echo off powershell -noprofile -executionPolicy RemoteSigned -file "%~dp0\check-for-loc-changes.ps1" %*
@echo off powershell -noprofile -executionPolicy RemoteSigned -file "%~dp0\check-for-loc-changes.ps1" %*
-1
dotnet/roslyn
55,419
Make vsix's compatible with vs 2022
Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
dibarbet
2021-08-04T23:36:41Z
2021-08-06T17:54:08Z
082df2aaf6a73277fc27f9d7a5a8d18ee45d7f8b
e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028
Make vsix's compatible with vs 2022. Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
./src/Features/LanguageServer/Protocol/Handler/SemanticTokens/SemanticTokensCache.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Roslyn.Utilities; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler.SemanticTokens { /// <summary> /// Caches the semantic token information that needs to be preserved between multiple /// semantic token requests. /// Multiple token sets can be cached per document. The number of token sets cached /// per document is determined by the _maxCachesPerDoc field. /// </summary> internal class SemanticTokensCache { /// <summary> /// Maps an LSP token type to the index LSP associates with the token. /// Required since we report tokens back to LSP as a series of ints, /// and LSP needs a way to decipher them. /// </summary> public static readonly Dictionary<string, int> TokenTypeToIndex; /// <summary> /// Number of cached token sets we store per document. Must be >= 1. /// </summary> private readonly int _maxCachesPerDoc = 5; /// <summary> /// The next resultId available to use. Atomically incremented with Interlocked, /// so this doesn't need to be protected by _semaphore. /// </summary> private long _nextResultId; /// <summary> /// Multiple cache requests or updates may be received concurrently. /// We need this sempahore to ensure that we aren't making concurrent /// modifications to the _tokens dictionary. /// </summary> private readonly SemaphoreSlim _semaphore = new(1); #region protected by _semaphore /// <summary> /// Maps a document URI to its n most recently cached token sets. /// </summary> private readonly Dictionary<Uri, List<LSP.SemanticTokens>> _tokens = new(); #endregion static SemanticTokensCache() { // Computes the mapping between a LSP token type and its respective index recognized by LSP. TokenTypeToIndex = new Dictionary<string, int>(); var index = 0; foreach (var lspTokenType in LSP.SemanticTokenTypes.AllTypes) { TokenTypeToIndex.Add(lspTokenType, index); index++; } foreach (var roslynTokenType in SemanticTokensHelpers.RoslynCustomTokenTypes) { TokenTypeToIndex.Add(roslynTokenType, index); index++; } } public SemanticTokensCache() { } /// <summary> /// Updates the given document's token set cache. Removes old cache results if the document's /// cache is full. /// </summary> public async Task UpdateCacheAsync( Uri uri, LSP.SemanticTokens tokens, CancellationToken cancellationToken) { Contract.ThrowIfNull(tokens.ResultId); using (await _semaphore.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { // Case 1: Document does not currently have any token sets cached. Create a cache // for the document and return. if (!_tokens.TryGetValue(uri, out var tokenSets)) { _tokens.Add(uri, new List<LSP.SemanticTokens> { tokens }); return; } // Case 2: Document already has the maximum number of token sets cached. Remove the // oldest token set from the cache, and then add the new token set (see case 3). if (tokenSets.Count >= _maxCachesPerDoc) { tokenSets.RemoveAt(0); } // Case 3: Document has less than the maximum number of token sets cached. // Add new token set to cache. tokenSets.Add(tokens); } } /// <summary> /// Returns the cached tokens data for a given document URI and resultId. /// Returns null if no match is found. /// </summary> public async Task<int[]?> GetCachedTokensDataAsync( Uri uri, string resultId, CancellationToken cancellationToken) { using (await _semaphore.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { if (!_tokens.TryGetValue(uri, out var tokenSets)) { return null; } // Return a non-null value only if the document's cache contains a token set with the resultId // that the user is searching for. return tokenSets.FirstOrDefault(t => t.ResultId == resultId)?.Data; } } /// <summary> /// Returns the next available resultId. /// </summary> public string GetNextResultId() => Interlocked.Increment(ref _nextResultId).ToString(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Roslyn.Utilities; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler.SemanticTokens { /// <summary> /// Caches the semantic token information that needs to be preserved between multiple /// semantic token requests. /// Multiple token sets can be cached per document. The number of token sets cached /// per document is determined by the _maxCachesPerDoc field. /// </summary> internal class SemanticTokensCache { /// <summary> /// Maps an LSP token type to the index LSP associates with the token. /// Required since we report tokens back to LSP as a series of ints, /// and LSP needs a way to decipher them. /// </summary> public static readonly Dictionary<string, int> TokenTypeToIndex; /// <summary> /// Number of cached token sets we store per document. Must be >= 1. /// </summary> private readonly int _maxCachesPerDoc = 5; /// <summary> /// The next resultId available to use. Atomically incremented with Interlocked, /// so this doesn't need to be protected by _semaphore. /// </summary> private long _nextResultId; /// <summary> /// Multiple cache requests or updates may be received concurrently. /// We need this sempahore to ensure that we aren't making concurrent /// modifications to the _tokens dictionary. /// </summary> private readonly SemaphoreSlim _semaphore = new(1); #region protected by _semaphore /// <summary> /// Maps a document URI to its n most recently cached token sets. /// </summary> private readonly Dictionary<Uri, List<LSP.SemanticTokens>> _tokens = new(); #endregion static SemanticTokensCache() { // Computes the mapping between a LSP token type and its respective index recognized by LSP. TokenTypeToIndex = new Dictionary<string, int>(); var index = 0; foreach (var lspTokenType in LSP.SemanticTokenTypes.AllTypes) { TokenTypeToIndex.Add(lspTokenType, index); index++; } foreach (var roslynTokenType in SemanticTokensHelpers.RoslynCustomTokenTypes) { TokenTypeToIndex.Add(roslynTokenType, index); index++; } } public SemanticTokensCache() { } /// <summary> /// Updates the given document's token set cache. Removes old cache results if the document's /// cache is full. /// </summary> public async Task UpdateCacheAsync( Uri uri, LSP.SemanticTokens tokens, CancellationToken cancellationToken) { Contract.ThrowIfNull(tokens.ResultId); using (await _semaphore.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { // Case 1: Document does not currently have any token sets cached. Create a cache // for the document and return. if (!_tokens.TryGetValue(uri, out var tokenSets)) { _tokens.Add(uri, new List<LSP.SemanticTokens> { tokens }); return; } // Case 2: Document already has the maximum number of token sets cached. Remove the // oldest token set from the cache, and then add the new token set (see case 3). if (tokenSets.Count >= _maxCachesPerDoc) { tokenSets.RemoveAt(0); } // Case 3: Document has less than the maximum number of token sets cached. // Add new token set to cache. tokenSets.Add(tokens); } } /// <summary> /// Returns the cached tokens data for a given document URI and resultId. /// Returns null if no match is found. /// </summary> public async Task<int[]?> GetCachedTokensDataAsync( Uri uri, string resultId, CancellationToken cancellationToken) { using (await _semaphore.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { if (!_tokens.TryGetValue(uri, out var tokenSets)) { return null; } // Return a non-null value only if the document's cache contains a token set with the resultId // that the user is searching for. return tokenSets.FirstOrDefault(t => t.ResultId == resultId)?.Data; } } /// <summary> /// Returns the next available resultId. /// </summary> public string GetNextResultId() => Interlocked.Increment(ref _nextResultId).ToString(); } }
-1
dotnet/roslyn
55,419
Make vsix's compatible with vs 2022
Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
dibarbet
2021-08-04T23:36:41Z
2021-08-06T17:54:08Z
082df2aaf6a73277fc27f9d7a5a8d18ee45d7f8b
e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028
Make vsix's compatible with vs 2022. Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
./src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_LateBindingHelpers.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Diagnostics Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend NotInheritable Class LocalRewriter ' returns receiver, or Nothing literal otherwise Private Function LateMakeReceiverArgument(node As SyntaxNode, rewrittenReceiver As BoundExpression, objectType As TypeSymbol) As BoundExpression Debug.Assert(objectType.IsObjectType) If rewrittenReceiver Is Nothing Then Return MakeNullLiteral(node, objectType) Else If Not rewrittenReceiver.Type.IsObjectType Then Dim useSiteInfo = GetNewCompoundUseSiteInfo() Dim convKind = Conversions.ClassifyDirectCastConversion(rewrittenReceiver.Type, objectType, useSiteInfo) _diagnostics.Add(node, useSiteInfo) rewrittenReceiver = New BoundDirectCast(node, rewrittenReceiver, convKind, objectType) End If Return rewrittenReceiver End If End Function ' returns GetType(Type) if receiver is nothing, or Nothing literal otherwise Private Function LateMakeContainerArgument(node As SyntaxNode, receiver As BoundExpression, containerType As TypeSymbol, typeType As TypeSymbol) As BoundExpression If receiver IsNot Nothing Then Return MakeNullLiteral(node, typeType) Else Return MakeGetTypeExpression(node, containerType, typeType) End If End Function ' returns "New Type(){GetType(Type1), GetType(Type2) ...} or Nothing literal Private Function LateMakeTypeArgumentArrayArgument(node As SyntaxNode, arguments As BoundTypeArguments, typeArrayType As TypeSymbol) As BoundExpression If arguments Is Nothing Then Return MakeNullLiteral(node, typeArrayType) Else Return MakeArrayOfGetTypeExpressions(node, arguments.Arguments, typeArrayType) End If End Function ' returns "New Boolean(length){} Private Function LateMakeCopyBackArray(node As SyntaxNode, flags As ImmutableArray(Of Boolean), booleanArrayType As TypeSymbol) As BoundExpression Dim arrayType = DirectCast(booleanArrayType, ArrayTypeSymbol) Dim booleanType = arrayType.ElementType Debug.Assert(arrayType.IsSZArray) Debug.Assert(booleanType.IsBooleanType) If flags.IsDefaultOrEmpty Then Return MakeNullLiteral(node, booleanArrayType) Else Dim intType = Me.GetSpecialType(SpecialType.System_Int32) Dim bounds As BoundExpression = New BoundLiteral(node, ConstantValue.Create(flags.Length), intType) Dim initializers = ArrayBuilder(Of BoundExpression).GetInstance For Each f In flags initializers.Add(MakeBooleanLiteral(node, f, booleanType)) Next Dim initializer = New BoundArrayInitialization(node, initializers.ToImmutableAndFree, Nothing) Return New BoundArrayCreation(node, ImmutableArray.Create(bounds), initializer, booleanArrayType) End If End Function Private Function LateMakeArgumentArrayArgument(node As SyntaxNode, rewrittenArguments As ImmutableArray(Of BoundExpression), argumentNames As ImmutableArray(Of String), objectArrayType As TypeSymbol) As BoundExpression If argumentNames.IsDefaultOrEmpty Then Return LateMakeArgumentArrayArgumentNoNamed(node, rewrittenArguments, objectArrayType) End If Dim namedArgNum As Integer = 0 Dim regularArgNum As Integer For Each name In argumentNames If name IsNot Nothing Then namedArgNum += 1 End If Next regularArgNum = rewrittenArguments.Length - namedArgNum Dim arrayType = DirectCast(objectArrayType, ArrayTypeSymbol) Dim objectType = arrayType.ElementType Debug.Assert(arrayType.IsSZArray) Debug.Assert(objectType.IsObjectType) Debug.Assert(Not rewrittenArguments.IsDefaultOrEmpty) Dim intType = Me.GetSpecialType(SpecialType.System_Int32) Dim bounds As BoundExpression = New BoundLiteral(node, ConstantValue.Create(rewrittenArguments.Length), intType) Dim arrayCreation = New BoundArrayCreation(node, ImmutableArray.Create(bounds), Nothing, objectArrayType) Dim arrayTemp As LocalSymbol = New SynthesizedLocal(Me._currentMethodOrLambda, arrayCreation.Type, SynthesizedLocalKind.LoweringTemp) Dim arrayTempRef = New BoundLocal(node, arrayTemp, arrayTemp.Type) Dim arrayInit = New BoundAssignmentOperator(node, arrayTempRef, arrayCreation, suppressObjectClone:=True) Dim sideeffects = ArrayBuilder(Of BoundExpression).GetInstance sideeffects.Add(arrayInit) arrayTempRef = arrayTempRef.MakeRValue For i As Integer = 0 To rewrittenArguments.Length - 1 Dim argument = rewrittenArguments(i) argument = argument.MakeRValue If Not argument.Type.IsObjectType Then Dim useSiteInfo = GetNewCompoundUseSiteInfo() Dim convKind = Conversions.ClassifyDirectCastConversion(argument.Type, objectType, useSiteInfo) _diagnostics.Add(node, useSiteInfo) argument = New BoundDirectCast(node, argument, convKind, objectType) End If ' named arguments are actually passed first in the array Dim indexVal = If(i < regularArgNum, namedArgNum + i, i - regularArgNum) Dim indexExpr As BoundExpression = New BoundLiteral(node, ConstantValue.Create(indexVal), intType) Dim indices = ImmutableArray.Create(indexExpr) Dim arrayElement As BoundExpression = New BoundArrayAccess(node, arrayTempRef, indices, objectType) Dim elementAssignment = New BoundAssignmentOperator(node, arrayElement, argument, suppressObjectClone:=True) sideeffects.Add(elementAssignment) Next Return New BoundSequence(node, ImmutableArray.Create(arrayTemp), sideeffects.ToImmutableAndFree, arrayTempRef, arrayTempRef.Type) End Function ' returns "New object(){Arg1, Arg2 ..., value} Private Function LateMakeSetArgumentArrayArgument(node As SyntaxNode, rewrittenValue As BoundExpression, rewrittenArguments As ImmutableArray(Of BoundExpression), argumentNames As ImmutableArray(Of String), objectArrayType As TypeSymbol) As BoundExpression Dim arrayType = DirectCast(objectArrayType, ArrayTypeSymbol) Dim objectType = arrayType.ElementType Debug.Assert(arrayType.IsSZArray) Debug.Assert(objectType.IsObjectType) Dim useSiteInfo = GetNewCompoundUseSiteInfo() If Not rewrittenValue.Type.IsObjectType Then Dim convKind = Conversions.ClassifyDirectCastConversion(rewrittenValue.Type, objectType, useSiteInfo) _diagnostics.Add(node, useSiteInfo) rewrittenValue = New BoundDirectCast(node, rewrittenValue, convKind, objectType) End If If argumentNames.IsDefaultOrEmpty Then If rewrittenArguments.IsDefaultOrEmpty Then rewrittenArguments = ImmutableArray.Create(rewrittenValue) ElseIf argumentNames.IsDefaultOrEmpty Then rewrittenArguments = rewrittenArguments.Add(rewrittenValue) End If Return LateMakeArgumentArrayArgumentNoNamed(node, rewrittenArguments, objectArrayType) End If ' have named arguments, need to reshuffle {named}{regular}{value} Dim namedArgNum As Integer = 0 Dim regularArgNum As Integer For Each name In argumentNames If name IsNot Nothing Then namedArgNum += 1 End If Next regularArgNum = rewrittenArguments.Length - namedArgNum Debug.Assert(Not rewrittenArguments.IsDefaultOrEmpty) Dim intType = Me.GetSpecialType(SpecialType.System_Int32) Dim bounds As BoundExpression = New BoundLiteral(node, ConstantValue.Create(rewrittenArguments.Length + 1), intType) Dim arrayCreation = New BoundArrayCreation(node, ImmutableArray.Create(bounds), Nothing, objectArrayType) Dim arrayTemp As LocalSymbol = New SynthesizedLocal(Me._currentMethodOrLambda, arrayCreation.Type, SynthesizedLocalKind.LoweringTemp) Dim arrayTempRef = New BoundLocal(node, arrayTemp, arrayTemp.Type) Dim arrayInit = New BoundAssignmentOperator(node, arrayTempRef, arrayCreation, suppressObjectClone:=True) Dim sideeffects = ArrayBuilder(Of BoundExpression).GetInstance sideeffects.Add(arrayInit) arrayTempRef = arrayTempRef.MakeRValue For i As Integer = 0 To rewrittenArguments.Length - 1 Dim argument = rewrittenArguments(i) argument = argument.MakeRValue If Not argument.Type.IsObjectType Then Dim convKind = Conversions.ClassifyDirectCastConversion(argument.Type, objectType, useSiteInfo) _diagnostics.Add(argument, useSiteInfo) argument = New BoundDirectCast(node, argument, convKind, objectType) End If ' named arguments are actually passed first in the array, then regular, then assignment value Dim indexVal = If(i < regularArgNum, namedArgNum + i, i - regularArgNum) Dim elementAssignment = LateAssignToArrayElement(node, arrayTempRef, indexVal, argument, intType) sideeffects.Add(elementAssignment) Next ' value goes last If Not rewrittenValue.Type.IsObjectType Then Dim convKind = Conversions.ClassifyDirectCastConversion(rewrittenValue.Type, objectType, useSiteInfo) _diagnostics.Add(rewrittenValue, useSiteInfo) rewrittenValue = New BoundDirectCast(node, rewrittenValue, convKind, objectType) End If Dim valueElementAssignment = LateAssignToArrayElement(node, arrayTempRef, rewrittenArguments.Length, rewrittenValue, intType) sideeffects.Add(valueElementAssignment) Return New BoundSequence(node, ImmutableArray.Create(arrayTemp), sideeffects.ToImmutableAndFree, arrayTempRef, arrayTempRef.Type) End Function Private Shared Function LateAssignToArrayElement(node As SyntaxNode, arrayRef As BoundExpression, index As Integer, value As BoundExpression, intType As TypeSymbol) As BoundExpression Dim indexExpr As BoundExpression = New BoundLiteral(node, ConstantValue.Create(index), intType) Dim arrayElement As BoundExpression = New BoundArrayAccess(node, arrayRef, ImmutableArray.Create(indexExpr), value.Type) Return New BoundAssignmentOperator(node, arrayElement, value, suppressObjectClone:=True) End Function ' returns "New object(){Arg1, Arg2 ...} Private Function LateMakeArgumentArrayArgumentNoNamed(node As SyntaxNode, rewrittenArguments As ImmutableArray(Of BoundExpression), objectArrayType As TypeSymbol) As BoundExpression Dim arrayType = DirectCast(objectArrayType, ArrayTypeSymbol) Dim objectType = arrayType.ElementType Dim intType = Me.GetSpecialType(SpecialType.System_Int32) Debug.Assert(arrayType.IsSZArray) Debug.Assert(objectType.IsObjectType) If rewrittenArguments.IsDefaultOrEmpty Then Dim bounds As BoundExpression = New BoundLiteral(node, ConstantValue.Default(ConstantValueTypeDiscriminator.Int32), intType) Return New BoundArrayCreation(node, ImmutableArray.Create(bounds), Nothing, objectArrayType) Else Dim bounds As BoundExpression = New BoundLiteral(node, ConstantValue.Create(rewrittenArguments.Length), intType) Dim initializers = ArrayBuilder(Of BoundExpression).GetInstance For Each argument In rewrittenArguments argument = argument.MakeRValue If Not argument.Type.IsObjectType Then Dim useSiteInfo = GetNewCompoundUseSiteInfo() Dim convKind = Conversions.ClassifyDirectCastConversion(argument.Type, objectType, useSiteInfo) _diagnostics.Add(argument, useSiteInfo) argument = New BoundDirectCast(node, argument, convKind, objectType) End If initializers.Add(argument) Next 'TODO: Dev11 does GetobjectValue here is it needed? Should array initialization do it in general? Dim initializer = New BoundArrayInitialization(node, initializers.ToImmutableAndFree, Nothing) Return New BoundArrayCreation(node, ImmutableArray.Create(bounds), initializer, objectArrayType) End If End Function ' returns "New object(){name1, name2 ...} or Nothing literal Private Function LateMakeArgumentNameArrayArgument(node As SyntaxNode, argumentNames As ImmutableArray(Of String), stringArrayType As TypeSymbol) As BoundExpression Dim arrayType = DirectCast(stringArrayType, ArrayTypeSymbol) Dim stringType = arrayType.ElementType Debug.Assert(arrayType.IsSZArray) Debug.Assert(stringType.IsStringType) If argumentNames.IsDefaultOrEmpty Then Return MakeNullLiteral(node, stringArrayType) Else Dim initializers = ArrayBuilder(Of BoundExpression).GetInstance For Each name In argumentNames If name IsNot Nothing Then initializers.Add(MakeStringLiteral(node, name, stringType)) Else Debug.Assert(initializers.Count = 0, "once we have named argument all following arguments must be named") End If Next Dim initializer = New BoundArrayInitialization(node, initializers.ToImmutableAndFree, Nothing) Dim intType = Me.GetSpecialType(SpecialType.System_Int32) Dim bounds As BoundExpression = New BoundLiteral(node, ConstantValue.Create(initializer.Initializers.Length), intType) Return New BoundArrayCreation(node, ImmutableArray.Create(bounds), initializer, stringArrayType) End If End Function ' Makes expressions like ' if(copyBackArrayRef[argNum], assignmentTarget := valueArrayRef[argNum] , Nothing) ' ' NOTE: assignmentTarget comes in not yet lowered. Private Function LateMakeConditionalCopyback(assignmentTarget As BoundExpression, valueArrayRef As BoundExpression, copyBackArrayRef As BoundExpression, argNum As Integer) As BoundExpression Dim syntax = assignmentTarget.Syntax Dim intType = Me.GetSpecialType(SpecialType.System_Int32) Dim index As BoundExpression = New BoundLiteral(syntax, ConstantValue.Create(argNum), intType) Dim indices = ImmutableArray.Create(index) Dim booleanType = DirectCast(copyBackArrayRef.Type, ArrayTypeSymbol).ElementType Dim condition As BoundExpression = New BoundArrayAccess(syntax, copyBackArrayRef, ImmutableArray.Create(index), booleanType).MakeRValue Dim objectType = DirectCast(valueArrayRef.Type, ArrayTypeSymbol).ElementType Dim value As BoundExpression = New BoundArrayAccess(syntax, valueArrayRef, indices, objectType).MakeRValue Dim targetType = assignmentTarget.Type If Not targetType.IsSameTypeIgnoringAll(objectType) Then ' // Call ChangeType to perform a latebound conversion Dim changeTypeMethod As MethodSymbol = Nothing If TryGetWellknownMember(changeTypeMethod, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ChangeType, syntax) Then ' value = ChangeType(value, GetType(targetType)) Dim getTypeExpr = New BoundGetType(syntax, New BoundTypeExpression(syntax, targetType), changeTypeMethod.Parameters(1).Type) 'TODO: should we suppress object clone here? Dev11 does not. value = New BoundCall(syntax, changeTypeMethod, Nothing, Nothing, ImmutableArray.Create(Of BoundExpression)(value, getTypeExpr), Nothing, suppressObjectClone:=False, type:=objectType) End If #If DEBUG Then Dim useSiteInfo As New CompoundUseSiteInfo(Of AssemblySymbol)(Me.Compilation.Assembly) #Else Dim useSiteInfo = CompoundUseSiteInfo(Of AssemblySymbol).Discarded #End If Dim conversionKind = Conversions.ClassifyDirectCastConversion(objectType, targetType, useSiteInfo) #If DEBUG Then Debug.Assert(useSiteInfo.Diagnostics.IsNullOrEmpty) Debug.Assert(useSiteInfo.Dependencies.IsNullOrEmpty) #End If value = New BoundDirectCast(syntax, value, conversionKind, targetType) End If Dim voidNoOp As BoundExpression = New BoundSequence(syntax, ImmutableArray(Of LocalSymbol).Empty, ImmutableArray(Of BoundExpression).Empty, Nothing, Me.GetSpecialType(SpecialType.System_Void)) Dim voidAssignment As BoundExpression = LateMakeCopyback(syntax, assignmentTarget, value) Dim result = MakeTernaryConditionalExpression(syntax, condition, voidAssignment, voidNoOp) Return VisitExpressionNode(result) End Function Private Function LateMakeCopyback(syntax As SyntaxNode, assignmentTarget As BoundExpression, convertedValue As BoundExpression) As BoundExpression If assignmentTarget.Kind = BoundKind.LateMemberAccess Then ' objExpr.goo = bar Dim memberAccess = DirectCast(assignmentTarget, BoundLateMemberAccess) Return LateSet(syntax, memberAccess, convertedValue, argExpressions:=Nothing, argNames:=Nothing, isCopyBack:=True) ElseIf assignmentTarget.Kind = BoundKind.LateInvocation Then Dim invocation = DirectCast(assignmentTarget, BoundLateInvocation) If invocation.Member.Kind = BoundKind.LateMemberAccess Then Dim memberAccess = DirectCast(invocation.Member, BoundLateMemberAccess) ' objExpr.goo(args) = bar Return LateSet(syntax, memberAccess, convertedValue, argExpressions:=invocation.ArgumentsOpt, argNames:=invocation.ArgumentNamesOpt, isCopyBack:=True) Else ' objExpr(args) = bar Return LateIndexSet(syntax, invocation, convertedValue, isCopyBack:=True) End If End If ' TODO: should we suppress object clone here? Dev11 does not suppress. Dim assignment As BoundExpression = New BoundAssignmentOperator(syntax, assignmentTarget, GenerateObjectCloneIfNeeded(convertedValue), suppressObjectClone:=True) Dim voidAssignment = New BoundSequence(syntax, ImmutableArray(Of LocalSymbol).Empty, ImmutableArray.Create(assignment), Nothing, Me.GetSpecialType(SpecialType.System_Void)) Return voidAssignment End Function Private Function LateIndexGet(node As BoundLateInvocation, receiverExpr As BoundExpression, argExpressions As ImmutableArray(Of BoundExpression)) As BoundExpression Debug.Assert(node.Member.Kind <> BoundKind.LateMemberAccess) ' We have ' objExpr(arg0, ..., argN) Dim syntax = node.Syntax ' expr = o.Goo<TypeParam> ' emit as: ' LateGet(invocation.Member, ' invocation.Arguments, ' invocation.ArgumentNames) ' ' Dim lateIndexGetMethod As MethodSymbol = Nothing If Not Me.TryGetWellknownMember(lateIndexGetMethod, WellKnownMember.Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateIndexGet, syntax) Then Return node End If ' arg0 "object Instance" Dim receiver As BoundExpression = LateMakeReceiverArgument(syntax, receiverExpr.MakeRValue, lateIndexGetMethod.Parameters(0).Type) ' arg1 "object[] Arguments" Dim arguments As BoundExpression = LateMakeArgumentArrayArgument(node.Syntax, argExpressions, node.ArgumentNamesOpt, lateIndexGetMethod.Parameters(1).Type) ' arg2 "string[] ArgumentNames" Dim argumentNames As BoundExpression = LateMakeArgumentNameArrayArgument(syntax, node.ArgumentNamesOpt, lateIndexGetMethod.Parameters(2).Type) Dim callArgs = ImmutableArray.Create(Of BoundExpression)(receiver, arguments, argumentNames) Dim callerInvocation As BoundExpression = New BoundCall( syntax, lateIndexGetMethod, Nothing, Nothing, callArgs, Nothing, suppressObjectClone:=True, type:=lateIndexGetMethod.ReturnType) Return callerInvocation End Function Private Function LateSet(syntax As SyntaxNode, memberAccess As BoundLateMemberAccess, assignmentValue As BoundExpression, argExpressions As ImmutableArray(Of BoundExpression), argNames As ImmutableArray(Of String), isCopyBack As Boolean) As BoundExpression Debug.Assert(memberAccess.AccessKind = LateBoundAccessKind.Set) ' TODO: May need a special case for parameters. ' A readonly parameter (in queries) may be not IsLValue, but Dev11 may treat it as an LValue still. ' NOTE: Dev11 passes "false" when access is static. We will do the same. ' It makes no difference at runtime since there is no base. Dim baseIsNotLValue As Boolean = memberAccess.ReceiverOpt IsNot Nothing AndAlso Not memberAccess.ReceiverOpt.IsLValue Dim lateSetMethod As MethodSymbol = Nothing Dim isComplex As Boolean = isCopyBack OrElse baseIsNotLValue If isComplex Then If Not Me.TryGetWellknownMember(lateSetMethod, WellKnownMember.Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateSetComplex, syntax) Then ' need to return something void Return New BoundSequence(syntax, ImmutableArray(Of LocalSymbol).Empty, ImmutableArray.Create(Of BoundExpression)(memberAccess), Nothing, Me.GetSpecialType(SpecialType.System_Void)) End If Else If Not Me.TryGetWellknownMember(lateSetMethod, WellKnownMember.Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateSet, syntax) Then ' need to return something void Return New BoundSequence(syntax, ImmutableArray(Of LocalSymbol).Empty, ImmutableArray.Create(Of BoundExpression)(memberAccess), Nothing, Me.GetSpecialType(SpecialType.System_Void)) End If End If ' arg0 "object Instance" Dim receiver As BoundExpression = LateMakeReceiverArgument(syntax, If(memberAccess.ReceiverOpt IsNot Nothing, memberAccess.ReceiverOpt.MakeRValue, Nothing), lateSetMethod.Parameters(0).Type) ' arg1 "Type Type" Dim containerType As BoundExpression = LateMakeContainerArgument(syntax, memberAccess.ReceiverOpt, memberAccess.ContainerTypeOpt, lateSetMethod.Parameters(1).Type) ' arg2 "string MemberName" Dim name As BoundLiteral = MakeStringLiteral(syntax, memberAccess.NameOpt, lateSetMethod.Parameters(2).Type) ' arg3 "object[] Arguments" Dim arguments As BoundExpression = LateMakeSetArgumentArrayArgument(syntax, assignmentValue, argExpressions, argNames, lateSetMethod.Parameters(3).Type) ' arg4 "string[] ArgumentNames" Dim argumentNames As BoundExpression = LateMakeArgumentNameArrayArgument(syntax, argNames, lateSetMethod.Parameters(4).Type) ' arg5 "Type[] TypeArguments" Dim typeArguments As BoundExpression = LateMakeTypeArgumentArrayArgument(syntax, memberAccess.TypeArgumentsOpt, lateSetMethod.Parameters(5).Type) Dim callArgs As ImmutableArray(Of BoundExpression) If Not isComplex Then callArgs = ImmutableArray.Create(Of BoundExpression)(receiver, containerType, name, arguments, argumentNames, typeArguments) Else ' arg6 "bool OptimisticSet" Dim optimisticSet As BoundExpression = MakeBooleanLiteral(syntax, isCopyBack, lateSetMethod.Parameters(6).Type) ' arg7 "bool RValueBase" Dim rValueBase As BoundExpression = MakeBooleanLiteral(syntax, baseIsNotLValue, lateSetMethod.Parameters(7).Type) callArgs = ImmutableArray.Create(Of BoundExpression)(receiver, containerType, name, arguments, argumentNames, typeArguments, optimisticSet, rValueBase) End If Return New BoundCall( syntax, lateSetMethod, Nothing, Nothing, callArgs, Nothing, suppressObjectClone:=True, type:=lateSetMethod.ReturnType) End Function Private Function LateIndexSet(syntax As SyntaxNode, invocation As BoundLateInvocation, assignmentValue As BoundExpression, isCopyBack As Boolean) As BoundExpression Debug.Assert(invocation.AccessKind = LateBoundAccessKind.Set) ' TODO: May need a special case for parameters. ' A readonly parameter (in queries) may be not IsLValue, but Dev11 may treat it as an LValue still. ' NOTE: Dev11 passes "false" when access is static. We will do the same. ' It makes no difference at runtime since there is no base. Dim baseIsNotLValue As Boolean = invocation.Member IsNot Nothing AndAlso Not invocation.Member.IsLValue Dim lateIndexSetMethod As MethodSymbol = Nothing Dim isComplex As Boolean = isCopyBack OrElse baseIsNotLValue If isComplex Then If Not Me.TryGetWellknownMember(lateIndexSetMethod, WellKnownMember.Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateIndexSetComplex, syntax) Then ' need to return something void Return New BoundSequence(syntax, ImmutableArray(Of LocalSymbol).Empty, ImmutableArray.Create(Of BoundExpression)(invocation), Nothing, Me.GetSpecialType(SpecialType.System_Void)) End If Else If Not Me.TryGetWellknownMember(lateIndexSetMethod, WellKnownMember.Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateIndexSet, syntax) Then ' need to return something void Return New BoundSequence(syntax, ImmutableArray(Of LocalSymbol).Empty, ImmutableArray.Create(Of BoundExpression)(invocation), Nothing, Me.GetSpecialType(SpecialType.System_Void)) End If End If ' arg0 "object Instance" Dim receiver As BoundExpression = LateMakeReceiverArgument(syntax, invocation.Member.MakeRValue, lateIndexSetMethod.Parameters(0).Type) ' arg1 "object[] Arguments" Dim arguments As BoundExpression = LateMakeSetArgumentArrayArgument(syntax, assignmentValue.MakeRValue, invocation.ArgumentsOpt, invocation.ArgumentNamesOpt, lateIndexSetMethod.Parameters(1).Type) ' arg2 "string[] ArgumentNames" Dim argumentNames As BoundExpression = LateMakeArgumentNameArrayArgument(syntax, invocation.ArgumentNamesOpt, lateIndexSetMethod.Parameters(2).Type) Dim callArgs As ImmutableArray(Of BoundExpression) If Not isComplex Then callArgs = ImmutableArray.Create(Of BoundExpression)(receiver, arguments, argumentNames) Else ' arg3 "bool OptimisticSet" Dim optimisticSet As BoundExpression = MakeBooleanLiteral(syntax, isCopyBack, lateIndexSetMethod.Parameters(3).Type) ' arg4 "bool RValueBase" Dim rValueBase As BoundExpression = MakeBooleanLiteral(syntax, baseIsNotLValue, lateIndexSetMethod.Parameters(4).Type) callArgs = ImmutableArray.Create(Of BoundExpression)(receiver, arguments, argumentNames, optimisticSet, rValueBase) End If Return New BoundCall( syntax, lateIndexSetMethod, Nothing, Nothing, callArgs, Nothing, suppressObjectClone:=True, type:=lateIndexSetMethod.ReturnType) End Function ' NOTE: assignmentArguments are no-side-effects expressions representing ' corresponding arguments if those need to be used as target of assignments. Private Function LateCallOrGet(memberAccess As BoundLateMemberAccess, receiverExpression As BoundExpression, argExpressions As ImmutableArray(Of BoundExpression), assignmentArguments As ImmutableArray(Of BoundExpression), argNames As ImmutableArray(Of String), useLateCall As Boolean) As BoundExpression Debug.Assert(memberAccess.AccessKind = LateBoundAccessKind.Call OrElse memberAccess.AccessKind = LateBoundAccessKind.Get) Debug.Assert((assignmentArguments.IsDefaultOrEmpty AndAlso argExpressions.IsDefaultOrEmpty) OrElse (assignmentArguments.Length = argExpressions.Length), "number of readable and writable arguments must match") Debug.Assert(argNames.IsDefaultOrEmpty OrElse argNames.Length = argExpressions.Length, "should not have argument names or should have name for every argument") Dim syntax = memberAccess.Syntax ' We have ' objExpr.Member() ' emit as: ' LateGet(memberAccess.ReceiverOpt, ' memberAccess.MemberContainerOpt, ' memberAccess.MemberNameOpt, ' Arguments:=Nothing, ' ArgumentNames:= Nothing, ' TypeArguments = memberAccess.TypeArguments) ' ' Dim lateCallOrGetMethod As MethodSymbol = Nothing If useLateCall Then If Not Me.TryGetWellknownMember(lateCallOrGetMethod, WellKnownMember.Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateCall, syntax) Then Return memberAccess End If Else If Not Me.TryGetWellknownMember(lateCallOrGetMethod, WellKnownMember.Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateGet, syntax) Then Return memberAccess End If End If ' temp will be used only if we have copybacks Dim valueArrayTemp As SynthesizedLocal = Nothing Dim valueArrayRef As BoundLocal = Nothing Dim copyBackFlagArrayTemp As SynthesizedLocal = Nothing Dim copyBackFlagArrayRef As BoundLocal = Nothing ' passed as an array that represents "arguments of the call" ' initially just rewrittenArgExpressions Dim argumentsArray As BoundExpression = LateMakeArgumentArrayArgument(syntax, argExpressions, argNames, lateCallOrGetMethod.Parameters(3).Type) ' passed as an array of flags indicating copyback status of corresponding elements of arguments array. ' initially Nothing Dim copyBackFlagArray As BoundExpression = LateMakeCopyBackArray(syntax, Nothing, lateCallOrGetMethod.Parameters(6).Type) '== process copybacks if needed Dim copyBackBuilder As ArrayBuilder(Of BoundExpression) = Nothing If Not assignmentArguments.IsDefaultOrEmpty Then Dim namedArgNum As Integer = 0 Dim regularArgNum As Integer If Not argNames.IsDefaultOrEmpty Then For Each n In argNames If n IsNot Nothing Then namedArgNum += 1 End If Next End If regularArgNum = assignmentArguments.Length - namedArgNum ' This is a Late Call/Get with arguments. ' All LValue arguments are presumed to be passed ByRef until rewriter assures us ' the other way (we do not know the refness of parameters at the callsite). ' if have any copybacks, need an array of bool the size of assignmentArguments.Count ' "True" conveys to the latebinder that the argument can accept copyback ' "False" means to not bother. ' During the actual call latebinder will erase True for arguments that ' happened to be passed to a ByVal parameter (so that we do not need to do copyback assignment on our side). Dim copyBackFlagValues As Boolean() = Nothing For i As Integer = 0 To assignmentArguments.Length - 1 Dim assignmentTarget As BoundExpression = assignmentArguments(i) If Not IsSupportingAssignment(assignmentTarget) Then Continue For End If If copyBackFlagArrayTemp Is Nothing Then ' since we may have copybacks, we need a temp for the flags array to examine its content after the call copyBackFlagArrayTemp = New SynthesizedLocal(Me._currentMethodOrLambda, copyBackFlagArray.Type, SynthesizedLocalKind.LoweringTemp) copyBackFlagArrayRef = (New BoundLocal(syntax, copyBackFlagArrayTemp, copyBackFlagArrayTemp.Type)).MakeRValue ' since we may have copybacks, we need a temp for the arguments array to access it after the call valueArrayTemp = New SynthesizedLocal(Me._currentMethodOrLambda, argumentsArray.Type, SynthesizedLocalKind.LoweringTemp) valueArrayRef = New BoundLocal(syntax, valueArrayTemp, valueArrayTemp.Type) argumentsArray = (New BoundAssignmentOperator(syntax, valueArrayRef, argumentsArray, suppressObjectClone:=True)).MakeRValue valueArrayRef = valueArrayRef.MakeRValue copyBackBuilder = ArrayBuilder(Of BoundExpression).GetInstance(assignmentArguments.Length) copyBackFlagValues = (New Boolean(assignmentArguments.Length - 1) {}) End If ' named arguments are actually passed first in the array Dim indexVal = If(i < regularArgNum, namedArgNum + i, i - regularArgNum) copyBackFlagValues(indexVal) = True copyBackBuilder.Add(LateMakeConditionalCopyback(assignmentTarget, valueArrayRef, copyBackFlagArrayRef, indexVal)) Next If copyBackFlagArrayTemp IsNot Nothing Then copyBackFlagArray = (New BoundAssignmentOperator(syntax, New BoundLocal(syntax, copyBackFlagArrayTemp, copyBackFlagArrayTemp.Type), LateMakeCopyBackArray(syntax, copyBackFlagValues.AsImmutableOrNull, copyBackFlagArrayTemp.Type), suppressObjectClone:=True)).MakeRValue End If End If Dim receiverValue As BoundExpression = If(receiverExpression Is Nothing, Nothing, receiverExpression.MakeRValue) ' arg0 "object Instance" Dim receiver As BoundExpression = LateMakeReceiverArgument(syntax, receiverValue, lateCallOrGetMethod.Parameters(0).Type) ' arg1 "Type Type" Dim containerType As BoundExpression = LateMakeContainerArgument(syntax, receiverExpression, memberAccess.ContainerTypeOpt, lateCallOrGetMethod.Parameters(1).Type) ' arg2 "string MemberName" Dim name As BoundLiteral = MakeStringLiteral(syntax, memberAccess.NameOpt, lateCallOrGetMethod.Parameters(2).Type) ' arg3 "object[] Arguments" Dim arguments As BoundExpression = argumentsArray ' arg4 "string[] ArgumentNames" Dim argumentNames As BoundExpression = LateMakeArgumentNameArrayArgument(syntax, argNames, lateCallOrGetMethod.Parameters(4).Type) ' arg5 "Type[] TypeArguments" Dim typeArguments As BoundExpression = LateMakeTypeArgumentArrayArgument(syntax, memberAccess.TypeArgumentsOpt, lateCallOrGetMethod.Parameters(5).Type) ' arg6 "bool[] CopyBack" Dim copyBack As BoundExpression = copyBackFlagArray Dim callArgs = ImmutableArray.Create(Of BoundExpression)(receiver, containerType, name, arguments, argumentNames, typeArguments, copyBack) ' ' It appears that IgnoreReturn is always set when LateCall is called from compiled code. ' ' @ Expressions.cpp/CodeGenerator::GenerateLate [line:3314] ' ... ' if (rtHelper == LateCallMember) ' { ' GenerateLiteralInt(COMPLUS_TRUE); ' } ' ... ' If useLateCall Then ' arg7 "bool IgnoreReturn" Dim ignoreReturn As BoundExpression = MakeBooleanLiteral(syntax, True, lateCallOrGetMethod.Parameters(7).Type) callArgs = callArgs.Add(ignoreReturn) End If Dim callerInvocation As BoundExpression = New BoundCall( syntax, lateCallOrGetMethod, Nothing, Nothing, callArgs, Nothing, suppressObjectClone:=True, type:=lateCallOrGetMethod.ReturnType) ' process copybacks If copyBackFlagArrayTemp IsNot Nothing Then Dim valueTemp = New SynthesizedLocal(Me._currentMethodOrLambda, callerInvocation.Type, SynthesizedLocalKind.LoweringTemp) Dim valueRef = New BoundLocal(syntax, valueTemp, valueTemp.Type) Dim store = New BoundAssignmentOperator(syntax, valueRef, callerInvocation, suppressObjectClone:=True) ' Seq{all temps; valueTemp = callerInvocation; copyBacks, valueTemp} callerInvocation = New BoundSequence(syntax, ImmutableArray.Create(Of LocalSymbol)(valueArrayTemp, copyBackFlagArrayTemp, valueTemp), ImmutableArray.Create(Of BoundExpression)(store).Concat(copyBackBuilder.ToImmutableAndFree), valueRef.MakeRValue, valueRef.Type) End If Return callerInvocation End Function ' same as LateCaptureReceiverAndArgsComplex, but without a receiver ' and does not produce reReadable arguments - just ' argument (that includes initialization of captures if needed) and a no-side-effect writable. ' NOTE: writables are not rewritten. They will be rewritten when they are combined with values into assignments. Private Sub LateCaptureArgsComplex(ByRef temps As ArrayBuilder(Of SynthesizedLocal), ByRef arguments As ImmutableArray(Of BoundExpression), <Out> ByRef writeTargets As ImmutableArray(Of BoundExpression)) Dim container = Me._currentMethodOrLambda If temps Is Nothing Then temps = ArrayBuilder(Of SynthesizedLocal).GetInstance End If If Not arguments.IsDefaultOrEmpty Then Dim argumentBuilder = ArrayBuilder(Of BoundExpression).GetInstance Dim writeTargetsBuilder = ArrayBuilder(Of BoundExpression).GetInstance For Each argument In arguments Dim writeTarget As BoundExpression If Not argument.IsSupportingAssignment() Then ' in this case writeTarget will not be used for assignment writeTarget = Nothing Else Dim argumentWithCapture As BoundLateBoundArgumentSupportingAssignmentWithCapture = Nothing If argument.Kind = BoundKind.LateBoundArgumentSupportingAssignmentWithCapture Then argumentWithCapture = DirectCast(argument, BoundLateBoundArgumentSupportingAssignmentWithCapture) argument = argumentWithCapture.OriginalArgument End If Dim useTwice = UseTwiceRewriter.UseTwice(container, argument, temps) If argument.IsPropertyOrXmlPropertyAccess Then argument = useTwice.First.SetAccessKind(PropertyAccessKind.Get) writeTarget = useTwice.Second.SetAccessKind(PropertyAccessKind.Set) ElseIf argument.IsLateBound() Then argument = useTwice.First.SetLateBoundAccessKind(LateBoundAccessKind.Get) writeTarget = useTwice.Second.SetLateBoundAccessKind(LateBoundAccessKind.Set) Else argument = useTwice.First.MakeRValue() writeTarget = useTwice.Second End If If argumentWithCapture IsNot Nothing Then argument = New BoundAssignmentOperator(argumentWithCapture.Syntax, New BoundLocal(argumentWithCapture.Syntax, argumentWithCapture.LocalSymbol, argumentWithCapture.LocalSymbol.Type), argument, suppressObjectClone:=True, type:=argumentWithCapture.Type) End If End If argumentBuilder.Add(VisitExpressionNode(argument)) writeTargetsBuilder.Add(writeTarget) Next arguments = argumentBuilder.ToImmutableAndFree writeTargets = writeTargetsBuilder.ToImmutableAndFree End If End Sub ' TODO: ' ================= GENERAL PURPOSE, MOVE TO COMMON FILE Private Shared Function MakeStringLiteral(node As SyntaxNode, value As String, stringType As TypeSymbol) As BoundLiteral If value Is Nothing Then Return MakeNullLiteral(node, stringType) Else Return New BoundLiteral(node, ConstantValue.Create(value), stringType) End If End Function Private Shared Function MakeBooleanLiteral(node As SyntaxNode, value As Boolean, booleanType As TypeSymbol) As BoundLiteral Return New BoundLiteral(node, ConstantValue.Create(value), booleanType) End Function Private Shared Function MakeGetTypeExpression(node As SyntaxNode, type As TypeSymbol, typeType As TypeSymbol) As BoundGetType Dim typeExpr = New BoundTypeExpression(node, type) Return New BoundGetType(node, typeExpr, typeType) End Function Private Function MakeArrayOfGetTypeExpressions(node As SyntaxNode, types As ImmutableArray(Of TypeSymbol), typeArrayType As TypeSymbol) As BoundArrayCreation Dim intType = Me.GetSpecialType(SpecialType.System_Int32) Dim bounds As BoundExpression = New BoundLiteral(node, ConstantValue.Create(types.Length), intType) Dim typeType = DirectCast(typeArrayType, ArrayTypeSymbol).ElementType Dim initializers = ArrayBuilder(Of BoundExpression).GetInstance For Each t In types initializers.Add(MakeGetTypeExpression(node, t, typeType)) Next Dim initializer = New BoundArrayInitialization(node, initializers.ToImmutableAndFree, Nothing) Return New BoundArrayCreation(node, ImmutableArray.Create(bounds), initializer, typeArrayType) End Function Private Function TryGetWellknownMember(Of T As Symbol)(<Out> ByRef result As T, memberId As WellKnownMember, syntax As SyntaxNode, Optional isOptional As Boolean = False) As Boolean result = Nothing Dim useSiteInfo As UseSiteInfo(Of AssemblySymbol) = Nothing Dim memberSymbol = Binder.GetWellKnownTypeMember(Me.Compilation, memberId, useSiteInfo) If useSiteInfo.DiagnosticInfo IsNot Nothing Then If Not isOptional Then Binder.ReportUseSite(_diagnostics, syntax.GetLocation(), useSiteInfo) End If Return False End If _diagnostics.AddDependencies(useSiteInfo) result = DirectCast(memberSymbol, T) Return True End Function ''' <summary> ''' Attempt to retrieve the specified special member, reporting a use-site diagnostic if the member is not found. ''' </summary> Private Function TryGetSpecialMember(Of T As Symbol)(<Out> ByRef result As T, memberId As SpecialMember, syntax As SyntaxNode) As Boolean result = Nothing Dim useSiteInfo As UseSiteInfo(Of AssemblySymbol) = Nothing Dim memberSymbol = Binder.GetSpecialTypeMember(Me._topMethod.ContainingAssembly, memberId, useSiteInfo) If Binder.ReportUseSite(_diagnostics, syntax.GetLocation(), useSiteInfo) Then Return False End If result = DirectCast(memberSymbol, T) Return True End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Diagnostics Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend NotInheritable Class LocalRewriter ' returns receiver, or Nothing literal otherwise Private Function LateMakeReceiverArgument(node As SyntaxNode, rewrittenReceiver As BoundExpression, objectType As TypeSymbol) As BoundExpression Debug.Assert(objectType.IsObjectType) If rewrittenReceiver Is Nothing Then Return MakeNullLiteral(node, objectType) Else If Not rewrittenReceiver.Type.IsObjectType Then Dim useSiteInfo = GetNewCompoundUseSiteInfo() Dim convKind = Conversions.ClassifyDirectCastConversion(rewrittenReceiver.Type, objectType, useSiteInfo) _diagnostics.Add(node, useSiteInfo) rewrittenReceiver = New BoundDirectCast(node, rewrittenReceiver, convKind, objectType) End If Return rewrittenReceiver End If End Function ' returns GetType(Type) if receiver is nothing, or Nothing literal otherwise Private Function LateMakeContainerArgument(node As SyntaxNode, receiver As BoundExpression, containerType As TypeSymbol, typeType As TypeSymbol) As BoundExpression If receiver IsNot Nothing Then Return MakeNullLiteral(node, typeType) Else Return MakeGetTypeExpression(node, containerType, typeType) End If End Function ' returns "New Type(){GetType(Type1), GetType(Type2) ...} or Nothing literal Private Function LateMakeTypeArgumentArrayArgument(node As SyntaxNode, arguments As BoundTypeArguments, typeArrayType As TypeSymbol) As BoundExpression If arguments Is Nothing Then Return MakeNullLiteral(node, typeArrayType) Else Return MakeArrayOfGetTypeExpressions(node, arguments.Arguments, typeArrayType) End If End Function ' returns "New Boolean(length){} Private Function LateMakeCopyBackArray(node As SyntaxNode, flags As ImmutableArray(Of Boolean), booleanArrayType As TypeSymbol) As BoundExpression Dim arrayType = DirectCast(booleanArrayType, ArrayTypeSymbol) Dim booleanType = arrayType.ElementType Debug.Assert(arrayType.IsSZArray) Debug.Assert(booleanType.IsBooleanType) If flags.IsDefaultOrEmpty Then Return MakeNullLiteral(node, booleanArrayType) Else Dim intType = Me.GetSpecialType(SpecialType.System_Int32) Dim bounds As BoundExpression = New BoundLiteral(node, ConstantValue.Create(flags.Length), intType) Dim initializers = ArrayBuilder(Of BoundExpression).GetInstance For Each f In flags initializers.Add(MakeBooleanLiteral(node, f, booleanType)) Next Dim initializer = New BoundArrayInitialization(node, initializers.ToImmutableAndFree, Nothing) Return New BoundArrayCreation(node, ImmutableArray.Create(bounds), initializer, booleanArrayType) End If End Function Private Function LateMakeArgumentArrayArgument(node As SyntaxNode, rewrittenArguments As ImmutableArray(Of BoundExpression), argumentNames As ImmutableArray(Of String), objectArrayType As TypeSymbol) As BoundExpression If argumentNames.IsDefaultOrEmpty Then Return LateMakeArgumentArrayArgumentNoNamed(node, rewrittenArguments, objectArrayType) End If Dim namedArgNum As Integer = 0 Dim regularArgNum As Integer For Each name In argumentNames If name IsNot Nothing Then namedArgNum += 1 End If Next regularArgNum = rewrittenArguments.Length - namedArgNum Dim arrayType = DirectCast(objectArrayType, ArrayTypeSymbol) Dim objectType = arrayType.ElementType Debug.Assert(arrayType.IsSZArray) Debug.Assert(objectType.IsObjectType) Debug.Assert(Not rewrittenArguments.IsDefaultOrEmpty) Dim intType = Me.GetSpecialType(SpecialType.System_Int32) Dim bounds As BoundExpression = New BoundLiteral(node, ConstantValue.Create(rewrittenArguments.Length), intType) Dim arrayCreation = New BoundArrayCreation(node, ImmutableArray.Create(bounds), Nothing, objectArrayType) Dim arrayTemp As LocalSymbol = New SynthesizedLocal(Me._currentMethodOrLambda, arrayCreation.Type, SynthesizedLocalKind.LoweringTemp) Dim arrayTempRef = New BoundLocal(node, arrayTemp, arrayTemp.Type) Dim arrayInit = New BoundAssignmentOperator(node, arrayTempRef, arrayCreation, suppressObjectClone:=True) Dim sideeffects = ArrayBuilder(Of BoundExpression).GetInstance sideeffects.Add(arrayInit) arrayTempRef = arrayTempRef.MakeRValue For i As Integer = 0 To rewrittenArguments.Length - 1 Dim argument = rewrittenArguments(i) argument = argument.MakeRValue If Not argument.Type.IsObjectType Then Dim useSiteInfo = GetNewCompoundUseSiteInfo() Dim convKind = Conversions.ClassifyDirectCastConversion(argument.Type, objectType, useSiteInfo) _diagnostics.Add(node, useSiteInfo) argument = New BoundDirectCast(node, argument, convKind, objectType) End If ' named arguments are actually passed first in the array Dim indexVal = If(i < regularArgNum, namedArgNum + i, i - regularArgNum) Dim indexExpr As BoundExpression = New BoundLiteral(node, ConstantValue.Create(indexVal), intType) Dim indices = ImmutableArray.Create(indexExpr) Dim arrayElement As BoundExpression = New BoundArrayAccess(node, arrayTempRef, indices, objectType) Dim elementAssignment = New BoundAssignmentOperator(node, arrayElement, argument, suppressObjectClone:=True) sideeffects.Add(elementAssignment) Next Return New BoundSequence(node, ImmutableArray.Create(arrayTemp), sideeffects.ToImmutableAndFree, arrayTempRef, arrayTempRef.Type) End Function ' returns "New object(){Arg1, Arg2 ..., value} Private Function LateMakeSetArgumentArrayArgument(node As SyntaxNode, rewrittenValue As BoundExpression, rewrittenArguments As ImmutableArray(Of BoundExpression), argumentNames As ImmutableArray(Of String), objectArrayType As TypeSymbol) As BoundExpression Dim arrayType = DirectCast(objectArrayType, ArrayTypeSymbol) Dim objectType = arrayType.ElementType Debug.Assert(arrayType.IsSZArray) Debug.Assert(objectType.IsObjectType) Dim useSiteInfo = GetNewCompoundUseSiteInfo() If Not rewrittenValue.Type.IsObjectType Then Dim convKind = Conversions.ClassifyDirectCastConversion(rewrittenValue.Type, objectType, useSiteInfo) _diagnostics.Add(node, useSiteInfo) rewrittenValue = New BoundDirectCast(node, rewrittenValue, convKind, objectType) End If If argumentNames.IsDefaultOrEmpty Then If rewrittenArguments.IsDefaultOrEmpty Then rewrittenArguments = ImmutableArray.Create(rewrittenValue) ElseIf argumentNames.IsDefaultOrEmpty Then rewrittenArguments = rewrittenArguments.Add(rewrittenValue) End If Return LateMakeArgumentArrayArgumentNoNamed(node, rewrittenArguments, objectArrayType) End If ' have named arguments, need to reshuffle {named}{regular}{value} Dim namedArgNum As Integer = 0 Dim regularArgNum As Integer For Each name In argumentNames If name IsNot Nothing Then namedArgNum += 1 End If Next regularArgNum = rewrittenArguments.Length - namedArgNum Debug.Assert(Not rewrittenArguments.IsDefaultOrEmpty) Dim intType = Me.GetSpecialType(SpecialType.System_Int32) Dim bounds As BoundExpression = New BoundLiteral(node, ConstantValue.Create(rewrittenArguments.Length + 1), intType) Dim arrayCreation = New BoundArrayCreation(node, ImmutableArray.Create(bounds), Nothing, objectArrayType) Dim arrayTemp As LocalSymbol = New SynthesizedLocal(Me._currentMethodOrLambda, arrayCreation.Type, SynthesizedLocalKind.LoweringTemp) Dim arrayTempRef = New BoundLocal(node, arrayTemp, arrayTemp.Type) Dim arrayInit = New BoundAssignmentOperator(node, arrayTempRef, arrayCreation, suppressObjectClone:=True) Dim sideeffects = ArrayBuilder(Of BoundExpression).GetInstance sideeffects.Add(arrayInit) arrayTempRef = arrayTempRef.MakeRValue For i As Integer = 0 To rewrittenArguments.Length - 1 Dim argument = rewrittenArguments(i) argument = argument.MakeRValue If Not argument.Type.IsObjectType Then Dim convKind = Conversions.ClassifyDirectCastConversion(argument.Type, objectType, useSiteInfo) _diagnostics.Add(argument, useSiteInfo) argument = New BoundDirectCast(node, argument, convKind, objectType) End If ' named arguments are actually passed first in the array, then regular, then assignment value Dim indexVal = If(i < regularArgNum, namedArgNum + i, i - regularArgNum) Dim elementAssignment = LateAssignToArrayElement(node, arrayTempRef, indexVal, argument, intType) sideeffects.Add(elementAssignment) Next ' value goes last If Not rewrittenValue.Type.IsObjectType Then Dim convKind = Conversions.ClassifyDirectCastConversion(rewrittenValue.Type, objectType, useSiteInfo) _diagnostics.Add(rewrittenValue, useSiteInfo) rewrittenValue = New BoundDirectCast(node, rewrittenValue, convKind, objectType) End If Dim valueElementAssignment = LateAssignToArrayElement(node, arrayTempRef, rewrittenArguments.Length, rewrittenValue, intType) sideeffects.Add(valueElementAssignment) Return New BoundSequence(node, ImmutableArray.Create(arrayTemp), sideeffects.ToImmutableAndFree, arrayTempRef, arrayTempRef.Type) End Function Private Shared Function LateAssignToArrayElement(node As SyntaxNode, arrayRef As BoundExpression, index As Integer, value As BoundExpression, intType As TypeSymbol) As BoundExpression Dim indexExpr As BoundExpression = New BoundLiteral(node, ConstantValue.Create(index), intType) Dim arrayElement As BoundExpression = New BoundArrayAccess(node, arrayRef, ImmutableArray.Create(indexExpr), value.Type) Return New BoundAssignmentOperator(node, arrayElement, value, suppressObjectClone:=True) End Function ' returns "New object(){Arg1, Arg2 ...} Private Function LateMakeArgumentArrayArgumentNoNamed(node As SyntaxNode, rewrittenArguments As ImmutableArray(Of BoundExpression), objectArrayType As TypeSymbol) As BoundExpression Dim arrayType = DirectCast(objectArrayType, ArrayTypeSymbol) Dim objectType = arrayType.ElementType Dim intType = Me.GetSpecialType(SpecialType.System_Int32) Debug.Assert(arrayType.IsSZArray) Debug.Assert(objectType.IsObjectType) If rewrittenArguments.IsDefaultOrEmpty Then Dim bounds As BoundExpression = New BoundLiteral(node, ConstantValue.Default(ConstantValueTypeDiscriminator.Int32), intType) Return New BoundArrayCreation(node, ImmutableArray.Create(bounds), Nothing, objectArrayType) Else Dim bounds As BoundExpression = New BoundLiteral(node, ConstantValue.Create(rewrittenArguments.Length), intType) Dim initializers = ArrayBuilder(Of BoundExpression).GetInstance For Each argument In rewrittenArguments argument = argument.MakeRValue If Not argument.Type.IsObjectType Then Dim useSiteInfo = GetNewCompoundUseSiteInfo() Dim convKind = Conversions.ClassifyDirectCastConversion(argument.Type, objectType, useSiteInfo) _diagnostics.Add(argument, useSiteInfo) argument = New BoundDirectCast(node, argument, convKind, objectType) End If initializers.Add(argument) Next 'TODO: Dev11 does GetobjectValue here is it needed? Should array initialization do it in general? Dim initializer = New BoundArrayInitialization(node, initializers.ToImmutableAndFree, Nothing) Return New BoundArrayCreation(node, ImmutableArray.Create(bounds), initializer, objectArrayType) End If End Function ' returns "New object(){name1, name2 ...} or Nothing literal Private Function LateMakeArgumentNameArrayArgument(node As SyntaxNode, argumentNames As ImmutableArray(Of String), stringArrayType As TypeSymbol) As BoundExpression Dim arrayType = DirectCast(stringArrayType, ArrayTypeSymbol) Dim stringType = arrayType.ElementType Debug.Assert(arrayType.IsSZArray) Debug.Assert(stringType.IsStringType) If argumentNames.IsDefaultOrEmpty Then Return MakeNullLiteral(node, stringArrayType) Else Dim initializers = ArrayBuilder(Of BoundExpression).GetInstance For Each name In argumentNames If name IsNot Nothing Then initializers.Add(MakeStringLiteral(node, name, stringType)) Else Debug.Assert(initializers.Count = 0, "once we have named argument all following arguments must be named") End If Next Dim initializer = New BoundArrayInitialization(node, initializers.ToImmutableAndFree, Nothing) Dim intType = Me.GetSpecialType(SpecialType.System_Int32) Dim bounds As BoundExpression = New BoundLiteral(node, ConstantValue.Create(initializer.Initializers.Length), intType) Return New BoundArrayCreation(node, ImmutableArray.Create(bounds), initializer, stringArrayType) End If End Function ' Makes expressions like ' if(copyBackArrayRef[argNum], assignmentTarget := valueArrayRef[argNum] , Nothing) ' ' NOTE: assignmentTarget comes in not yet lowered. Private Function LateMakeConditionalCopyback(assignmentTarget As BoundExpression, valueArrayRef As BoundExpression, copyBackArrayRef As BoundExpression, argNum As Integer) As BoundExpression Dim syntax = assignmentTarget.Syntax Dim intType = Me.GetSpecialType(SpecialType.System_Int32) Dim index As BoundExpression = New BoundLiteral(syntax, ConstantValue.Create(argNum), intType) Dim indices = ImmutableArray.Create(index) Dim booleanType = DirectCast(copyBackArrayRef.Type, ArrayTypeSymbol).ElementType Dim condition As BoundExpression = New BoundArrayAccess(syntax, copyBackArrayRef, ImmutableArray.Create(index), booleanType).MakeRValue Dim objectType = DirectCast(valueArrayRef.Type, ArrayTypeSymbol).ElementType Dim value As BoundExpression = New BoundArrayAccess(syntax, valueArrayRef, indices, objectType).MakeRValue Dim targetType = assignmentTarget.Type If Not targetType.IsSameTypeIgnoringAll(objectType) Then ' // Call ChangeType to perform a latebound conversion Dim changeTypeMethod As MethodSymbol = Nothing If TryGetWellknownMember(changeTypeMethod, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ChangeType, syntax) Then ' value = ChangeType(value, GetType(targetType)) Dim getTypeExpr = New BoundGetType(syntax, New BoundTypeExpression(syntax, targetType), changeTypeMethod.Parameters(1).Type) 'TODO: should we suppress object clone here? Dev11 does not. value = New BoundCall(syntax, changeTypeMethod, Nothing, Nothing, ImmutableArray.Create(Of BoundExpression)(value, getTypeExpr), Nothing, suppressObjectClone:=False, type:=objectType) End If #If DEBUG Then Dim useSiteInfo As New CompoundUseSiteInfo(Of AssemblySymbol)(Me.Compilation.Assembly) #Else Dim useSiteInfo = CompoundUseSiteInfo(Of AssemblySymbol).Discarded #End If Dim conversionKind = Conversions.ClassifyDirectCastConversion(objectType, targetType, useSiteInfo) #If DEBUG Then Debug.Assert(useSiteInfo.Diagnostics.IsNullOrEmpty) Debug.Assert(useSiteInfo.Dependencies.IsNullOrEmpty) #End If value = New BoundDirectCast(syntax, value, conversionKind, targetType) End If Dim voidNoOp As BoundExpression = New BoundSequence(syntax, ImmutableArray(Of LocalSymbol).Empty, ImmutableArray(Of BoundExpression).Empty, Nothing, Me.GetSpecialType(SpecialType.System_Void)) Dim voidAssignment As BoundExpression = LateMakeCopyback(syntax, assignmentTarget, value) Dim result = MakeTernaryConditionalExpression(syntax, condition, voidAssignment, voidNoOp) Return VisitExpressionNode(result) End Function Private Function LateMakeCopyback(syntax As SyntaxNode, assignmentTarget As BoundExpression, convertedValue As BoundExpression) As BoundExpression If assignmentTarget.Kind = BoundKind.LateMemberAccess Then ' objExpr.goo = bar Dim memberAccess = DirectCast(assignmentTarget, BoundLateMemberAccess) Return LateSet(syntax, memberAccess, convertedValue, argExpressions:=Nothing, argNames:=Nothing, isCopyBack:=True) ElseIf assignmentTarget.Kind = BoundKind.LateInvocation Then Dim invocation = DirectCast(assignmentTarget, BoundLateInvocation) If invocation.Member.Kind = BoundKind.LateMemberAccess Then Dim memberAccess = DirectCast(invocation.Member, BoundLateMemberAccess) ' objExpr.goo(args) = bar Return LateSet(syntax, memberAccess, convertedValue, argExpressions:=invocation.ArgumentsOpt, argNames:=invocation.ArgumentNamesOpt, isCopyBack:=True) Else ' objExpr(args) = bar Return LateIndexSet(syntax, invocation, convertedValue, isCopyBack:=True) End If End If ' TODO: should we suppress object clone here? Dev11 does not suppress. Dim assignment As BoundExpression = New BoundAssignmentOperator(syntax, assignmentTarget, GenerateObjectCloneIfNeeded(convertedValue), suppressObjectClone:=True) Dim voidAssignment = New BoundSequence(syntax, ImmutableArray(Of LocalSymbol).Empty, ImmutableArray.Create(assignment), Nothing, Me.GetSpecialType(SpecialType.System_Void)) Return voidAssignment End Function Private Function LateIndexGet(node As BoundLateInvocation, receiverExpr As BoundExpression, argExpressions As ImmutableArray(Of BoundExpression)) As BoundExpression Debug.Assert(node.Member.Kind <> BoundKind.LateMemberAccess) ' We have ' objExpr(arg0, ..., argN) Dim syntax = node.Syntax ' expr = o.Goo<TypeParam> ' emit as: ' LateGet(invocation.Member, ' invocation.Arguments, ' invocation.ArgumentNames) ' ' Dim lateIndexGetMethod As MethodSymbol = Nothing If Not Me.TryGetWellknownMember(lateIndexGetMethod, WellKnownMember.Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateIndexGet, syntax) Then Return node End If ' arg0 "object Instance" Dim receiver As BoundExpression = LateMakeReceiverArgument(syntax, receiverExpr.MakeRValue, lateIndexGetMethod.Parameters(0).Type) ' arg1 "object[] Arguments" Dim arguments As BoundExpression = LateMakeArgumentArrayArgument(node.Syntax, argExpressions, node.ArgumentNamesOpt, lateIndexGetMethod.Parameters(1).Type) ' arg2 "string[] ArgumentNames" Dim argumentNames As BoundExpression = LateMakeArgumentNameArrayArgument(syntax, node.ArgumentNamesOpt, lateIndexGetMethod.Parameters(2).Type) Dim callArgs = ImmutableArray.Create(Of BoundExpression)(receiver, arguments, argumentNames) Dim callerInvocation As BoundExpression = New BoundCall( syntax, lateIndexGetMethod, Nothing, Nothing, callArgs, Nothing, suppressObjectClone:=True, type:=lateIndexGetMethod.ReturnType) Return callerInvocation End Function Private Function LateSet(syntax As SyntaxNode, memberAccess As BoundLateMemberAccess, assignmentValue As BoundExpression, argExpressions As ImmutableArray(Of BoundExpression), argNames As ImmutableArray(Of String), isCopyBack As Boolean) As BoundExpression Debug.Assert(memberAccess.AccessKind = LateBoundAccessKind.Set) ' TODO: May need a special case for parameters. ' A readonly parameter (in queries) may be not IsLValue, but Dev11 may treat it as an LValue still. ' NOTE: Dev11 passes "false" when access is static. We will do the same. ' It makes no difference at runtime since there is no base. Dim baseIsNotLValue As Boolean = memberAccess.ReceiverOpt IsNot Nothing AndAlso Not memberAccess.ReceiverOpt.IsLValue Dim lateSetMethod As MethodSymbol = Nothing Dim isComplex As Boolean = isCopyBack OrElse baseIsNotLValue If isComplex Then If Not Me.TryGetWellknownMember(lateSetMethod, WellKnownMember.Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateSetComplex, syntax) Then ' need to return something void Return New BoundSequence(syntax, ImmutableArray(Of LocalSymbol).Empty, ImmutableArray.Create(Of BoundExpression)(memberAccess), Nothing, Me.GetSpecialType(SpecialType.System_Void)) End If Else If Not Me.TryGetWellknownMember(lateSetMethod, WellKnownMember.Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateSet, syntax) Then ' need to return something void Return New BoundSequence(syntax, ImmutableArray(Of LocalSymbol).Empty, ImmutableArray.Create(Of BoundExpression)(memberAccess), Nothing, Me.GetSpecialType(SpecialType.System_Void)) End If End If ' arg0 "object Instance" Dim receiver As BoundExpression = LateMakeReceiverArgument(syntax, If(memberAccess.ReceiverOpt IsNot Nothing, memberAccess.ReceiverOpt.MakeRValue, Nothing), lateSetMethod.Parameters(0).Type) ' arg1 "Type Type" Dim containerType As BoundExpression = LateMakeContainerArgument(syntax, memberAccess.ReceiverOpt, memberAccess.ContainerTypeOpt, lateSetMethod.Parameters(1).Type) ' arg2 "string MemberName" Dim name As BoundLiteral = MakeStringLiteral(syntax, memberAccess.NameOpt, lateSetMethod.Parameters(2).Type) ' arg3 "object[] Arguments" Dim arguments As BoundExpression = LateMakeSetArgumentArrayArgument(syntax, assignmentValue, argExpressions, argNames, lateSetMethod.Parameters(3).Type) ' arg4 "string[] ArgumentNames" Dim argumentNames As BoundExpression = LateMakeArgumentNameArrayArgument(syntax, argNames, lateSetMethod.Parameters(4).Type) ' arg5 "Type[] TypeArguments" Dim typeArguments As BoundExpression = LateMakeTypeArgumentArrayArgument(syntax, memberAccess.TypeArgumentsOpt, lateSetMethod.Parameters(5).Type) Dim callArgs As ImmutableArray(Of BoundExpression) If Not isComplex Then callArgs = ImmutableArray.Create(Of BoundExpression)(receiver, containerType, name, arguments, argumentNames, typeArguments) Else ' arg6 "bool OptimisticSet" Dim optimisticSet As BoundExpression = MakeBooleanLiteral(syntax, isCopyBack, lateSetMethod.Parameters(6).Type) ' arg7 "bool RValueBase" Dim rValueBase As BoundExpression = MakeBooleanLiteral(syntax, baseIsNotLValue, lateSetMethod.Parameters(7).Type) callArgs = ImmutableArray.Create(Of BoundExpression)(receiver, containerType, name, arguments, argumentNames, typeArguments, optimisticSet, rValueBase) End If Return New BoundCall( syntax, lateSetMethod, Nothing, Nothing, callArgs, Nothing, suppressObjectClone:=True, type:=lateSetMethod.ReturnType) End Function Private Function LateIndexSet(syntax As SyntaxNode, invocation As BoundLateInvocation, assignmentValue As BoundExpression, isCopyBack As Boolean) As BoundExpression Debug.Assert(invocation.AccessKind = LateBoundAccessKind.Set) ' TODO: May need a special case for parameters. ' A readonly parameter (in queries) may be not IsLValue, but Dev11 may treat it as an LValue still. ' NOTE: Dev11 passes "false" when access is static. We will do the same. ' It makes no difference at runtime since there is no base. Dim baseIsNotLValue As Boolean = invocation.Member IsNot Nothing AndAlso Not invocation.Member.IsLValue Dim lateIndexSetMethod As MethodSymbol = Nothing Dim isComplex As Boolean = isCopyBack OrElse baseIsNotLValue If isComplex Then If Not Me.TryGetWellknownMember(lateIndexSetMethod, WellKnownMember.Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateIndexSetComplex, syntax) Then ' need to return something void Return New BoundSequence(syntax, ImmutableArray(Of LocalSymbol).Empty, ImmutableArray.Create(Of BoundExpression)(invocation), Nothing, Me.GetSpecialType(SpecialType.System_Void)) End If Else If Not Me.TryGetWellknownMember(lateIndexSetMethod, WellKnownMember.Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateIndexSet, syntax) Then ' need to return something void Return New BoundSequence(syntax, ImmutableArray(Of LocalSymbol).Empty, ImmutableArray.Create(Of BoundExpression)(invocation), Nothing, Me.GetSpecialType(SpecialType.System_Void)) End If End If ' arg0 "object Instance" Dim receiver As BoundExpression = LateMakeReceiverArgument(syntax, invocation.Member.MakeRValue, lateIndexSetMethod.Parameters(0).Type) ' arg1 "object[] Arguments" Dim arguments As BoundExpression = LateMakeSetArgumentArrayArgument(syntax, assignmentValue.MakeRValue, invocation.ArgumentsOpt, invocation.ArgumentNamesOpt, lateIndexSetMethod.Parameters(1).Type) ' arg2 "string[] ArgumentNames" Dim argumentNames As BoundExpression = LateMakeArgumentNameArrayArgument(syntax, invocation.ArgumentNamesOpt, lateIndexSetMethod.Parameters(2).Type) Dim callArgs As ImmutableArray(Of BoundExpression) If Not isComplex Then callArgs = ImmutableArray.Create(Of BoundExpression)(receiver, arguments, argumentNames) Else ' arg3 "bool OptimisticSet" Dim optimisticSet As BoundExpression = MakeBooleanLiteral(syntax, isCopyBack, lateIndexSetMethod.Parameters(3).Type) ' arg4 "bool RValueBase" Dim rValueBase As BoundExpression = MakeBooleanLiteral(syntax, baseIsNotLValue, lateIndexSetMethod.Parameters(4).Type) callArgs = ImmutableArray.Create(Of BoundExpression)(receiver, arguments, argumentNames, optimisticSet, rValueBase) End If Return New BoundCall( syntax, lateIndexSetMethod, Nothing, Nothing, callArgs, Nothing, suppressObjectClone:=True, type:=lateIndexSetMethod.ReturnType) End Function ' NOTE: assignmentArguments are no-side-effects expressions representing ' corresponding arguments if those need to be used as target of assignments. Private Function LateCallOrGet(memberAccess As BoundLateMemberAccess, receiverExpression As BoundExpression, argExpressions As ImmutableArray(Of BoundExpression), assignmentArguments As ImmutableArray(Of BoundExpression), argNames As ImmutableArray(Of String), useLateCall As Boolean) As BoundExpression Debug.Assert(memberAccess.AccessKind = LateBoundAccessKind.Call OrElse memberAccess.AccessKind = LateBoundAccessKind.Get) Debug.Assert((assignmentArguments.IsDefaultOrEmpty AndAlso argExpressions.IsDefaultOrEmpty) OrElse (assignmentArguments.Length = argExpressions.Length), "number of readable and writable arguments must match") Debug.Assert(argNames.IsDefaultOrEmpty OrElse argNames.Length = argExpressions.Length, "should not have argument names or should have name for every argument") Dim syntax = memberAccess.Syntax ' We have ' objExpr.Member() ' emit as: ' LateGet(memberAccess.ReceiverOpt, ' memberAccess.MemberContainerOpt, ' memberAccess.MemberNameOpt, ' Arguments:=Nothing, ' ArgumentNames:= Nothing, ' TypeArguments = memberAccess.TypeArguments) ' ' Dim lateCallOrGetMethod As MethodSymbol = Nothing If useLateCall Then If Not Me.TryGetWellknownMember(lateCallOrGetMethod, WellKnownMember.Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateCall, syntax) Then Return memberAccess End If Else If Not Me.TryGetWellknownMember(lateCallOrGetMethod, WellKnownMember.Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateGet, syntax) Then Return memberAccess End If End If ' temp will be used only if we have copybacks Dim valueArrayTemp As SynthesizedLocal = Nothing Dim valueArrayRef As BoundLocal = Nothing Dim copyBackFlagArrayTemp As SynthesizedLocal = Nothing Dim copyBackFlagArrayRef As BoundLocal = Nothing ' passed as an array that represents "arguments of the call" ' initially just rewrittenArgExpressions Dim argumentsArray As BoundExpression = LateMakeArgumentArrayArgument(syntax, argExpressions, argNames, lateCallOrGetMethod.Parameters(3).Type) ' passed as an array of flags indicating copyback status of corresponding elements of arguments array. ' initially Nothing Dim copyBackFlagArray As BoundExpression = LateMakeCopyBackArray(syntax, Nothing, lateCallOrGetMethod.Parameters(6).Type) '== process copybacks if needed Dim copyBackBuilder As ArrayBuilder(Of BoundExpression) = Nothing If Not assignmentArguments.IsDefaultOrEmpty Then Dim namedArgNum As Integer = 0 Dim regularArgNum As Integer If Not argNames.IsDefaultOrEmpty Then For Each n In argNames If n IsNot Nothing Then namedArgNum += 1 End If Next End If regularArgNum = assignmentArguments.Length - namedArgNum ' This is a Late Call/Get with arguments. ' All LValue arguments are presumed to be passed ByRef until rewriter assures us ' the other way (we do not know the refness of parameters at the callsite). ' if have any copybacks, need an array of bool the size of assignmentArguments.Count ' "True" conveys to the latebinder that the argument can accept copyback ' "False" means to not bother. ' During the actual call latebinder will erase True for arguments that ' happened to be passed to a ByVal parameter (so that we do not need to do copyback assignment on our side). Dim copyBackFlagValues As Boolean() = Nothing For i As Integer = 0 To assignmentArguments.Length - 1 Dim assignmentTarget As BoundExpression = assignmentArguments(i) If Not IsSupportingAssignment(assignmentTarget) Then Continue For End If If copyBackFlagArrayTemp Is Nothing Then ' since we may have copybacks, we need a temp for the flags array to examine its content after the call copyBackFlagArrayTemp = New SynthesizedLocal(Me._currentMethodOrLambda, copyBackFlagArray.Type, SynthesizedLocalKind.LoweringTemp) copyBackFlagArrayRef = (New BoundLocal(syntax, copyBackFlagArrayTemp, copyBackFlagArrayTemp.Type)).MakeRValue ' since we may have copybacks, we need a temp for the arguments array to access it after the call valueArrayTemp = New SynthesizedLocal(Me._currentMethodOrLambda, argumentsArray.Type, SynthesizedLocalKind.LoweringTemp) valueArrayRef = New BoundLocal(syntax, valueArrayTemp, valueArrayTemp.Type) argumentsArray = (New BoundAssignmentOperator(syntax, valueArrayRef, argumentsArray, suppressObjectClone:=True)).MakeRValue valueArrayRef = valueArrayRef.MakeRValue copyBackBuilder = ArrayBuilder(Of BoundExpression).GetInstance(assignmentArguments.Length) copyBackFlagValues = (New Boolean(assignmentArguments.Length - 1) {}) End If ' named arguments are actually passed first in the array Dim indexVal = If(i < regularArgNum, namedArgNum + i, i - regularArgNum) copyBackFlagValues(indexVal) = True copyBackBuilder.Add(LateMakeConditionalCopyback(assignmentTarget, valueArrayRef, copyBackFlagArrayRef, indexVal)) Next If copyBackFlagArrayTemp IsNot Nothing Then copyBackFlagArray = (New BoundAssignmentOperator(syntax, New BoundLocal(syntax, copyBackFlagArrayTemp, copyBackFlagArrayTemp.Type), LateMakeCopyBackArray(syntax, copyBackFlagValues.AsImmutableOrNull, copyBackFlagArrayTemp.Type), suppressObjectClone:=True)).MakeRValue End If End If Dim receiverValue As BoundExpression = If(receiverExpression Is Nothing, Nothing, receiverExpression.MakeRValue) ' arg0 "object Instance" Dim receiver As BoundExpression = LateMakeReceiverArgument(syntax, receiverValue, lateCallOrGetMethod.Parameters(0).Type) ' arg1 "Type Type" Dim containerType As BoundExpression = LateMakeContainerArgument(syntax, receiverExpression, memberAccess.ContainerTypeOpt, lateCallOrGetMethod.Parameters(1).Type) ' arg2 "string MemberName" Dim name As BoundLiteral = MakeStringLiteral(syntax, memberAccess.NameOpt, lateCallOrGetMethod.Parameters(2).Type) ' arg3 "object[] Arguments" Dim arguments As BoundExpression = argumentsArray ' arg4 "string[] ArgumentNames" Dim argumentNames As BoundExpression = LateMakeArgumentNameArrayArgument(syntax, argNames, lateCallOrGetMethod.Parameters(4).Type) ' arg5 "Type[] TypeArguments" Dim typeArguments As BoundExpression = LateMakeTypeArgumentArrayArgument(syntax, memberAccess.TypeArgumentsOpt, lateCallOrGetMethod.Parameters(5).Type) ' arg6 "bool[] CopyBack" Dim copyBack As BoundExpression = copyBackFlagArray Dim callArgs = ImmutableArray.Create(Of BoundExpression)(receiver, containerType, name, arguments, argumentNames, typeArguments, copyBack) ' ' It appears that IgnoreReturn is always set when LateCall is called from compiled code. ' ' @ Expressions.cpp/CodeGenerator::GenerateLate [line:3314] ' ... ' if (rtHelper == LateCallMember) ' { ' GenerateLiteralInt(COMPLUS_TRUE); ' } ' ... ' If useLateCall Then ' arg7 "bool IgnoreReturn" Dim ignoreReturn As BoundExpression = MakeBooleanLiteral(syntax, True, lateCallOrGetMethod.Parameters(7).Type) callArgs = callArgs.Add(ignoreReturn) End If Dim callerInvocation As BoundExpression = New BoundCall( syntax, lateCallOrGetMethod, Nothing, Nothing, callArgs, Nothing, suppressObjectClone:=True, type:=lateCallOrGetMethod.ReturnType) ' process copybacks If copyBackFlagArrayTemp IsNot Nothing Then Dim valueTemp = New SynthesizedLocal(Me._currentMethodOrLambda, callerInvocation.Type, SynthesizedLocalKind.LoweringTemp) Dim valueRef = New BoundLocal(syntax, valueTemp, valueTemp.Type) Dim store = New BoundAssignmentOperator(syntax, valueRef, callerInvocation, suppressObjectClone:=True) ' Seq{all temps; valueTemp = callerInvocation; copyBacks, valueTemp} callerInvocation = New BoundSequence(syntax, ImmutableArray.Create(Of LocalSymbol)(valueArrayTemp, copyBackFlagArrayTemp, valueTemp), ImmutableArray.Create(Of BoundExpression)(store).Concat(copyBackBuilder.ToImmutableAndFree), valueRef.MakeRValue, valueRef.Type) End If Return callerInvocation End Function ' same as LateCaptureReceiverAndArgsComplex, but without a receiver ' and does not produce reReadable arguments - just ' argument (that includes initialization of captures if needed) and a no-side-effect writable. ' NOTE: writables are not rewritten. They will be rewritten when they are combined with values into assignments. Private Sub LateCaptureArgsComplex(ByRef temps As ArrayBuilder(Of SynthesizedLocal), ByRef arguments As ImmutableArray(Of BoundExpression), <Out> ByRef writeTargets As ImmutableArray(Of BoundExpression)) Dim container = Me._currentMethodOrLambda If temps Is Nothing Then temps = ArrayBuilder(Of SynthesizedLocal).GetInstance End If If Not arguments.IsDefaultOrEmpty Then Dim argumentBuilder = ArrayBuilder(Of BoundExpression).GetInstance Dim writeTargetsBuilder = ArrayBuilder(Of BoundExpression).GetInstance For Each argument In arguments Dim writeTarget As BoundExpression If Not argument.IsSupportingAssignment() Then ' in this case writeTarget will not be used for assignment writeTarget = Nothing Else Dim argumentWithCapture As BoundLateBoundArgumentSupportingAssignmentWithCapture = Nothing If argument.Kind = BoundKind.LateBoundArgumentSupportingAssignmentWithCapture Then argumentWithCapture = DirectCast(argument, BoundLateBoundArgumentSupportingAssignmentWithCapture) argument = argumentWithCapture.OriginalArgument End If Dim useTwice = UseTwiceRewriter.UseTwice(container, argument, temps) If argument.IsPropertyOrXmlPropertyAccess Then argument = useTwice.First.SetAccessKind(PropertyAccessKind.Get) writeTarget = useTwice.Second.SetAccessKind(PropertyAccessKind.Set) ElseIf argument.IsLateBound() Then argument = useTwice.First.SetLateBoundAccessKind(LateBoundAccessKind.Get) writeTarget = useTwice.Second.SetLateBoundAccessKind(LateBoundAccessKind.Set) Else argument = useTwice.First.MakeRValue() writeTarget = useTwice.Second End If If argumentWithCapture IsNot Nothing Then argument = New BoundAssignmentOperator(argumentWithCapture.Syntax, New BoundLocal(argumentWithCapture.Syntax, argumentWithCapture.LocalSymbol, argumentWithCapture.LocalSymbol.Type), argument, suppressObjectClone:=True, type:=argumentWithCapture.Type) End If End If argumentBuilder.Add(VisitExpressionNode(argument)) writeTargetsBuilder.Add(writeTarget) Next arguments = argumentBuilder.ToImmutableAndFree writeTargets = writeTargetsBuilder.ToImmutableAndFree End If End Sub ' TODO: ' ================= GENERAL PURPOSE, MOVE TO COMMON FILE Private Shared Function MakeStringLiteral(node As SyntaxNode, value As String, stringType As TypeSymbol) As BoundLiteral If value Is Nothing Then Return MakeNullLiteral(node, stringType) Else Return New BoundLiteral(node, ConstantValue.Create(value), stringType) End If End Function Private Shared Function MakeBooleanLiteral(node As SyntaxNode, value As Boolean, booleanType As TypeSymbol) As BoundLiteral Return New BoundLiteral(node, ConstantValue.Create(value), booleanType) End Function Private Shared Function MakeGetTypeExpression(node As SyntaxNode, type As TypeSymbol, typeType As TypeSymbol) As BoundGetType Dim typeExpr = New BoundTypeExpression(node, type) Return New BoundGetType(node, typeExpr, typeType) End Function Private Function MakeArrayOfGetTypeExpressions(node As SyntaxNode, types As ImmutableArray(Of TypeSymbol), typeArrayType As TypeSymbol) As BoundArrayCreation Dim intType = Me.GetSpecialType(SpecialType.System_Int32) Dim bounds As BoundExpression = New BoundLiteral(node, ConstantValue.Create(types.Length), intType) Dim typeType = DirectCast(typeArrayType, ArrayTypeSymbol).ElementType Dim initializers = ArrayBuilder(Of BoundExpression).GetInstance For Each t In types initializers.Add(MakeGetTypeExpression(node, t, typeType)) Next Dim initializer = New BoundArrayInitialization(node, initializers.ToImmutableAndFree, Nothing) Return New BoundArrayCreation(node, ImmutableArray.Create(bounds), initializer, typeArrayType) End Function Private Function TryGetWellknownMember(Of T As Symbol)(<Out> ByRef result As T, memberId As WellKnownMember, syntax As SyntaxNode, Optional isOptional As Boolean = False) As Boolean result = Nothing Dim useSiteInfo As UseSiteInfo(Of AssemblySymbol) = Nothing Dim memberSymbol = Binder.GetWellKnownTypeMember(Me.Compilation, memberId, useSiteInfo) If useSiteInfo.DiagnosticInfo IsNot Nothing Then If Not isOptional Then Binder.ReportUseSite(_diagnostics, syntax.GetLocation(), useSiteInfo) End If Return False End If _diagnostics.AddDependencies(useSiteInfo) result = DirectCast(memberSymbol, T) Return True End Function ''' <summary> ''' Attempt to retrieve the specified special member, reporting a use-site diagnostic if the member is not found. ''' </summary> Private Function TryGetSpecialMember(Of T As Symbol)(<Out> ByRef result As T, memberId As SpecialMember, syntax As SyntaxNode) As Boolean result = Nothing Dim useSiteInfo As UseSiteInfo(Of AssemblySymbol) = Nothing Dim memberSymbol = Binder.GetSpecialTypeMember(Me._topMethod.ContainingAssembly, memberId, useSiteInfo) If Binder.ReportUseSite(_diagnostics, syntax.GetLocation(), useSiteInfo) Then Return False End If result = DirectCast(memberSymbol, T) Return True End Function End Class End Namespace
-1
dotnet/roslyn
55,419
Make vsix's compatible with vs 2022
Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
dibarbet
2021-08-04T23:36:41Z
2021-08-06T17:54:08Z
082df2aaf6a73277fc27f9d7a5a8d18ee45d7f8b
e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028
Make vsix's compatible with vs 2022. Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
./src/Compilers/CSharp/Portable/CodeGen/EmitStatement.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection.Metadata; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CSharp.Binder; namespace Microsoft.CodeAnalysis.CSharp.CodeGen { internal partial class CodeGenerator { private void EmitStatement(BoundStatement statement) { switch (statement.Kind) { case BoundKind.Block: EmitBlock((BoundBlock)statement); break; case BoundKind.Scope: EmitScope((BoundScope)statement); break; case BoundKind.SequencePoint: this.EmitSequencePointStatement((BoundSequencePoint)statement); break; case BoundKind.SequencePointWithSpan: this.EmitSequencePointStatement((BoundSequencePointWithSpan)statement); break; case BoundKind.SavePreviousSequencePoint: this.EmitSavePreviousSequencePoint((BoundSavePreviousSequencePoint)statement); break; case BoundKind.RestorePreviousSequencePoint: this.EmitRestorePreviousSequencePoint((BoundRestorePreviousSequencePoint)statement); break; case BoundKind.StepThroughSequencePoint: this.EmitStepThroughSequencePoint((BoundStepThroughSequencePoint)statement); break; case BoundKind.ExpressionStatement: EmitExpression(((BoundExpressionStatement)statement).Expression, false); break; case BoundKind.StatementList: EmitStatementList((BoundStatementList)statement); break; case BoundKind.ReturnStatement: EmitReturnStatement((BoundReturnStatement)statement); break; case BoundKind.GotoStatement: EmitGotoStatement((BoundGotoStatement)statement); break; case BoundKind.LabelStatement: EmitLabelStatement((BoundLabelStatement)statement); break; case BoundKind.ConditionalGoto: EmitConditionalGoto((BoundConditionalGoto)statement); break; case BoundKind.ThrowStatement: EmitThrowStatement((BoundThrowStatement)statement); break; case BoundKind.TryStatement: EmitTryStatement((BoundTryStatement)statement); break; case BoundKind.SwitchDispatch: EmitSwitchDispatch((BoundSwitchDispatch)statement); break; case BoundKind.StateMachineScope: EmitStateMachineScope((BoundStateMachineScope)statement); break; case BoundKind.NoOpStatement: EmitNoOpStatement((BoundNoOpStatement)statement); break; default: // Code gen should not be invoked if there are errors. throw ExceptionUtilities.UnexpectedValue(statement.Kind); } #if DEBUG if (_stackLocals == null || _stackLocals.Count == 0) { _builder.AssertStackEmpty(); } #endif ReleaseExpressionTemps(); } private int EmitStatementAndCountInstructions(BoundStatement statement) { int n = _builder.InstructionsEmitted; this.EmitStatement(statement); return _builder.InstructionsEmitted - n; } private void EmitStatementList(BoundStatementList list) { for (int i = 0, n = list.Statements.Length; i < n; i++) { EmitStatement(list.Statements[i]); } } private void EmitNoOpStatement(BoundNoOpStatement statement) { switch (statement.Flavor) { case NoOpStatementFlavor.Default: if (_ilEmitStyle == ILEmitStyle.Debug) { _builder.EmitOpCode(ILOpCode.Nop); } break; case NoOpStatementFlavor.AwaitYieldPoint: Debug.Assert((_asyncYieldPoints == null) == (_asyncResumePoints == null)); if (_asyncYieldPoints == null) { _asyncYieldPoints = ArrayBuilder<int>.GetInstance(); _asyncResumePoints = ArrayBuilder<int>.GetInstance(); } Debug.Assert(_asyncYieldPoints.Count == _asyncResumePoints.Count); _asyncYieldPoints.Add(_builder.AllocateILMarker()); break; case NoOpStatementFlavor.AwaitResumePoint: Debug.Assert(_asyncYieldPoints != null); Debug.Assert(_asyncYieldPoints != null); _asyncResumePoints.Add(_builder.AllocateILMarker()); Debug.Assert(_asyncYieldPoints.Count == _asyncResumePoints.Count); break; default: throw ExceptionUtilities.UnexpectedValue(statement.Flavor); } } private void EmitThrowStatement(BoundThrowStatement node) { EmitThrow(node.ExpressionOpt); } private void EmitThrow(BoundExpression thrown) { if (thrown != null) { this.EmitExpression(thrown, true); var exprType = thrown.Type; // Expression type will be null for "throw null;". if (exprType?.TypeKind == TypeKind.TypeParameter) { this.EmitBox(exprType, thrown.Syntax); } } _builder.EmitThrow(isRethrow: thrown == null); } private void EmitConditionalGoto(BoundConditionalGoto boundConditionalGoto) { object label = boundConditionalGoto.Label; Debug.Assert(label != null); EmitCondBranch(boundConditionalGoto.Condition, ref label, boundConditionalGoto.JumpIfTrue); } // 3.17 The brfalse instruction transfers control to target if value (of type int32, int64, object reference, managed //pointer, unmanaged pointer or native int) is zero (false). If value is non-zero (true), execution continues at //the next instruction. private static bool CanPassToBrfalse(TypeSymbol ts) { if (ts.IsEnumType()) { // valid enums are all primitives return true; } var tc = ts.PrimitiveTypeCode; switch (tc) { case Microsoft.Cci.PrimitiveTypeCode.Float32: case Microsoft.Cci.PrimitiveTypeCode.Float64: return false; case Microsoft.Cci.PrimitiveTypeCode.NotPrimitive: // if this is a generic type param, verifier will want us to box // EmitCondBranch knows that return ts.IsReferenceType; default: Debug.Assert(tc != Microsoft.Cci.PrimitiveTypeCode.Invalid); Debug.Assert(tc != Microsoft.Cci.PrimitiveTypeCode.Void); return true; } } private static BoundExpression TryReduce(BoundBinaryOperator condition, ref bool sense) { var opKind = condition.OperatorKind.Operator(); Debug.Assert(opKind == BinaryOperatorKind.Equal || opKind == BinaryOperatorKind.NotEqual); BoundExpression nonConstOp; BoundExpression constOp = (condition.Left.ConstantValue != null) ? condition.Left : null; if (constOp != null) { nonConstOp = condition.Right; } else { constOp = (condition.Right.ConstantValue != null) ? condition.Right : null; if (constOp == null) { return null; } nonConstOp = condition.Left; } var nonConstType = nonConstOp.Type; if (!CanPassToBrfalse(nonConstType)) { return null; } bool isBool = nonConstType.PrimitiveTypeCode == Microsoft.Cci.PrimitiveTypeCode.Boolean; bool isZero = constOp.ConstantValue.IsDefaultValue; // bool is special, only it can be compared to true and false... if (!isBool && !isZero) { return null; } // if comparing to zero, flip the sense if (isZero) { sense = !sense; } // if comparing != flip the sense if (opKind == BinaryOperatorKind.NotEqual) { sense = !sense; } return nonConstOp; } private const int IL_OP_CODE_ROW_LENGTH = 4; private static readonly ILOpCode[] s_condJumpOpCodes = new ILOpCode[] { // < <= > >= ILOpCode.Blt, ILOpCode.Ble, ILOpCode.Bgt, ILOpCode.Bge, // Signed ILOpCode.Bge, ILOpCode.Bgt, ILOpCode.Ble, ILOpCode.Blt, // Signed Invert ILOpCode.Blt_un, ILOpCode.Ble_un, ILOpCode.Bgt_un, ILOpCode.Bge_un, // Unsigned ILOpCode.Bge_un, ILOpCode.Bgt_un, ILOpCode.Ble_un, ILOpCode.Blt_un, // Unsigned Invert ILOpCode.Blt, ILOpCode.Ble, ILOpCode.Bgt, ILOpCode.Bge, // Float ILOpCode.Bge_un, ILOpCode.Bgt_un, ILOpCode.Ble_un, ILOpCode.Blt_un, // Float Invert }; /// <summary> /// Produces opcode for a jump that corresponds to given operation and sense. /// Also produces a reverse opcode - opcode for the same condition with inverted sense. /// </summary> private static ILOpCode CodeForJump(BoundBinaryOperator op, bool sense, out ILOpCode revOpCode) { int opIdx; switch (op.OperatorKind.Operator()) { case BinaryOperatorKind.Equal: revOpCode = !sense ? ILOpCode.Beq : ILOpCode.Bne_un; return sense ? ILOpCode.Beq : ILOpCode.Bne_un; case BinaryOperatorKind.NotEqual: revOpCode = !sense ? ILOpCode.Bne_un : ILOpCode.Beq; return sense ? ILOpCode.Bne_un : ILOpCode.Beq; case BinaryOperatorKind.LessThan: opIdx = 0; break; case BinaryOperatorKind.LessThanOrEqual: opIdx = 1; break; case BinaryOperatorKind.GreaterThan: opIdx = 2; break; case BinaryOperatorKind.GreaterThanOrEqual: opIdx = 3; break; default: throw ExceptionUtilities.UnexpectedValue(op.OperatorKind.Operator()); } if (IsUnsignedBinaryOperator(op)) { opIdx += 2 * IL_OP_CODE_ROW_LENGTH; //unsigned } else if (IsFloat(op.OperatorKind)) { opIdx += 4 * IL_OP_CODE_ROW_LENGTH; //float } int revOpIdx = opIdx; if (!sense) { opIdx += IL_OP_CODE_ROW_LENGTH; //invert op } else { revOpIdx += IL_OP_CODE_ROW_LENGTH; //invert rev } revOpCode = s_condJumpOpCodes[revOpIdx]; return s_condJumpOpCodes[opIdx]; } // generate a jump to dest if (condition == sense) is true private void EmitCondBranch(BoundExpression condition, ref object dest, bool sense) { _recursionDepth++; if (_recursionDepth > 1) { StackGuard.EnsureSufficientExecutionStack(_recursionDepth); EmitCondBranchCore(condition, ref dest, sense); } else { EmitCondBranchCoreWithStackGuard(condition, ref dest, sense); } _recursionDepth--; } private void EmitCondBranchCoreWithStackGuard(BoundExpression condition, ref object dest, bool sense) { Debug.Assert(_recursionDepth == 1); try { EmitCondBranchCore(condition, ref dest, sense); Debug.Assert(_recursionDepth == 1); } catch (InsufficientExecutionStackException) { _diagnostics.Add(ErrorCode.ERR_InsufficientStack, BoundTreeVisitor.CancelledByStackGuardException.GetTooLongOrComplexExpressionErrorLocation(condition)); throw new EmitCancelledException(); } } private void EmitCondBranchCore(BoundExpression condition, ref object dest, bool sense) { oneMoreTime: ILOpCode ilcode; if (condition.ConstantValue != null) { bool taken = condition.ConstantValue.IsDefaultValue != sense; if (taken) { dest = dest ?? new object(); _builder.EmitBranch(ILOpCode.Br, dest); } else { // otherwise this branch will never be taken, so just fall through... } return; } switch (condition.Kind) { case BoundKind.BinaryOperator: var binOp = (BoundBinaryOperator)condition; bool testBothArgs = sense; switch (binOp.OperatorKind.OperatorWithLogical()) { case BinaryOperatorKind.LogicalOr: testBothArgs = !testBothArgs; // Fall through goto case BinaryOperatorKind.LogicalAnd; case BinaryOperatorKind.LogicalAnd: if (testBothArgs) { // gotoif(a != sense) fallThrough // gotoif(b == sense) dest // fallThrough: object fallThrough = null; EmitCondBranch(binOp.Left, ref fallThrough, !sense); EmitCondBranch(binOp.Right, ref dest, sense); if (fallThrough != null) { _builder.MarkLabel(fallThrough); } } else { // gotoif(a == sense) labDest // gotoif(b == sense) labDest EmitCondBranch(binOp.Left, ref dest, sense); condition = binOp.Right; goto oneMoreTime; } return; case BinaryOperatorKind.Equal: case BinaryOperatorKind.NotEqual: var reduced = TryReduce(binOp, ref sense); if (reduced != null) { condition = reduced; goto oneMoreTime; } // Fall through goto case BinaryOperatorKind.LessThan; case BinaryOperatorKind.LessThan: case BinaryOperatorKind.LessThanOrEqual: case BinaryOperatorKind.GreaterThan: case BinaryOperatorKind.GreaterThanOrEqual: EmitExpression(binOp.Left, true); EmitExpression(binOp.Right, true); ILOpCode revOpCode; ilcode = CodeForJump(binOp, sense, out revOpCode); dest = dest ?? new object(); _builder.EmitBranch(ilcode, dest, revOpCode); return; } // none of above. // then it is regular binary expression - Or, And, Xor ... goto default; case BoundKind.LoweredConditionalAccess: { var ca = (BoundLoweredConditionalAccess)condition; var receiver = ca.Receiver; var receiverType = receiver.Type; // we need a copy if we deal with nonlocal value (to capture the value) // or if we deal with stack local (reads are destructive) var complexCase = !receiverType.IsReferenceType || LocalRewriter.CanChangeValueBetweenReads(receiver, localsMayBeAssignedOrCaptured: false) || (receiver.Kind == BoundKind.Local && IsStackLocal(((BoundLocal)receiver).LocalSymbol)) || (ca.WhenNullOpt?.IsDefaultValue() == false); if (complexCase) { goto default; } if (sense) { // gotoif(receiver != null) fallThrough // gotoif(receiver.Access) dest // fallThrough: object fallThrough = null; EmitCondBranch(receiver, ref fallThrough, sense: false); // receiver is a reference type, and we only intend to read it EmitReceiverRef(receiver, AddressKind.ReadOnly); EmitCondBranch(ca.WhenNotNull, ref dest, sense: true); if (fallThrough != null) { _builder.MarkLabel(fallThrough); } } else { // gotoif(receiver == null) labDest // gotoif(!receiver.Access) labDest EmitCondBranch(receiver, ref dest, sense: false); // receiver is a reference type, and we only intend to read it EmitReceiverRef(receiver, AddressKind.ReadOnly); condition = ca.WhenNotNull; goto oneMoreTime; } } return; case BoundKind.UnaryOperator: var unOp = (BoundUnaryOperator)condition; if (unOp.OperatorKind == UnaryOperatorKind.BoolLogicalNegation) { sense = !sense; condition = unOp.Operand; goto oneMoreTime; } goto default; case BoundKind.IsOperator: var isOp = (BoundIsOperator)condition; var operand = isOp.Operand; EmitExpression(operand, true); Debug.Assert((object)operand.Type != null); if (!operand.Type.IsVerifierReference()) { // box the operand for isinst if it is not a verifier reference EmitBox(operand.Type, operand.Syntax); } _builder.EmitOpCode(ILOpCode.Isinst); EmitSymbolToken(isOp.TargetType.Type, isOp.TargetType.Syntax); ilcode = sense ? ILOpCode.Brtrue : ILOpCode.Brfalse; dest = dest ?? new object(); _builder.EmitBranch(ilcode, dest); return; case BoundKind.Sequence: var seq = (BoundSequence)condition; EmitSequenceCondBranch(seq, ref dest, sense); return; default: EmitExpression(condition, true); var conditionType = condition.Type; if (conditionType.IsReferenceType && !conditionType.IsVerifierReference()) { EmitBox(conditionType, condition.Syntax); } ilcode = sense ? ILOpCode.Brtrue : ILOpCode.Brfalse; dest = dest ?? new object(); _builder.EmitBranch(ilcode, dest); return; } } private void EmitSequenceCondBranch(BoundSequence sequence, ref object dest, bool sense) { DefineLocals(sequence); EmitSideEffects(sequence); EmitCondBranch(sequence.Value, ref dest, sense); // sequence is used as a value, can release all locals FreeLocals(sequence); } private void EmitLabelStatement(BoundLabelStatement boundLabelStatement) { _builder.MarkLabel(boundLabelStatement.Label); } private void EmitGotoStatement(BoundGotoStatement boundGotoStatement) { _builder.EmitBranch(ILOpCode.Br, boundGotoStatement.Label); } // used by HandleReturn method which tries to inject // indirect ret sequence as a last statement in the block // that is the last statement of the current method // NOTE: it is important that there is no code after this "ret" // it is desirable, for debug purposes, that this ret is emitted inside top level { } private bool IsLastBlockInMethod(BoundBlock block) { if (_boundBody == block) { return true; } //sometimes top level node is a statement list containing //epilogue and then a block. If we are having that block, it will do. var list = _boundBody as BoundStatementList; if (list != null && list.Statements.LastOrDefault() == block) { return true; } return false; } private void EmitBlock(BoundBlock block) { var hasLocals = !block.Locals.IsEmpty; if (hasLocals) { _builder.OpenLocalScope(); foreach (var local in block.Locals) { Debug.Assert(local.RefKind == RefKind.None || local.SynthesizedKind.IsLongLived(), "A ref local ended up in a block and claims it is shortlived. That is dangerous. Are we sure it is short lived?"); var declaringReferences = local.DeclaringSyntaxReferences; DefineLocal(local, !declaringReferences.IsEmpty ? (CSharpSyntaxNode)declaringReferences[0].GetSyntax() : block.Syntax); } } EmitStatements(block.Statements); if (_indirectReturnState == IndirectReturnState.Needed && IsLastBlockInMethod(block)) { HandleReturn(); } if (hasLocals) { foreach (var local in block.Locals) { FreeLocal(local); } _builder.CloseLocalScope(); } } private void EmitStatements(ImmutableArray<BoundStatement> statements) { foreach (var statement in statements) { EmitStatement(statement); } } private void EmitScope(BoundScope block) { Debug.Assert(!block.Locals.IsEmpty); _builder.OpenLocalScope(); foreach (var local in block.Locals) { Debug.Assert(local.Name != null); Debug.Assert(local.SynthesizedKind == SynthesizedLocalKind.UserDefined && (local.ScopeDesignatorOpt?.Kind() == SyntaxKind.SwitchSection || local.ScopeDesignatorOpt?.Kind() == SyntaxKind.SwitchExpressionArm)); if (!local.IsConst && !IsStackLocal(local)) { _builder.AddLocalToScope(_builder.LocalSlotManager.GetLocal(local)); } } EmitStatements(block.Statements); _builder.CloseLocalScope(); } private void EmitStateMachineScope(BoundStateMachineScope scope) { _builder.OpenLocalScope(ScopeType.StateMachineVariable); foreach (var field in scope.Fields) { _builder.DefineUserDefinedStateMachineHoistedLocal(field.SlotIndex); } EmitStatement(scope.Statement); _builder.CloseLocalScope(); } // There are two ways a value can be returned from a function: // - Using ret opcode // - Store return value if any to a predefined temp and jump to the epilogue block // Sometimes ret is not an option (try/catch etc.). We also do this when emitting // debuggable code. This function is a stub for the logic that decides that. private bool ShouldUseIndirectReturn() { // If the method/lambda body is a block we define a sequence point for the closing brace of the body // and associate it with the ret instruction. If there is a return statement we need to store the value // to a long-lived synthesized local since a sequence point requires an empty evaluation stack. // // The emitted pattern is: // <evaluate return statement expression> // stloc $ReturnValue // ldloc $ReturnValue // sequence point // ret // // Do not emit this pattern if the method doesn't include user code or doesn't have a block body. return _ilEmitStyle == ILEmitStyle.Debug && _method.GenerateDebugInfo && _methodBodySyntaxOpt?.IsKind(SyntaxKind.Block) == true || _builder.InExceptionHandler; } // Compiler generated return mapped to a block is very likely the synthetic return // that was added at the end of the last block of a void method by analysis. // This is likely to be the last return in the method, so if we have not yet // emitted return sequence, it is convenient to do it right here (if we can). private bool CanHandleReturnLabel(BoundReturnStatement boundReturnStatement) { return boundReturnStatement.WasCompilerGenerated && (boundReturnStatement.Syntax.IsKind(SyntaxKind.Block) || _method?.IsImplicitConstructor == true) && !_builder.InExceptionHandler; } private void EmitReturnStatement(BoundReturnStatement boundReturnStatement) { var expressionOpt = boundReturnStatement.ExpressionOpt; if (boundReturnStatement.RefKind == RefKind.None) { this.EmitExpression(expressionOpt, true); } else { // NOTE: passing "ReadOnlyStrict" here. // we should never return an address of a copy var unexpectedTemp = this.EmitAddress(expressionOpt, this._method.RefKind == RefKind.RefReadOnly ? AddressKind.ReadOnlyStrict : AddressKind.Writeable); Debug.Assert(unexpectedTemp == null, "ref-returning a temp?"); } if (ShouldUseIndirectReturn()) { if (expressionOpt != null) { _builder.EmitLocalStore(LazyReturnTemp); } if (_indirectReturnState != IndirectReturnState.Emitted && CanHandleReturnLabel(boundReturnStatement)) { HandleReturn(); } else { _builder.EmitBranch(ILOpCode.Br, s_returnLabel); if (_indirectReturnState == IndirectReturnState.NotNeeded) { _indirectReturnState = IndirectReturnState.Needed; } } } else { if (_indirectReturnState == IndirectReturnState.Needed && CanHandleReturnLabel(boundReturnStatement)) { if (expressionOpt != null) { _builder.EmitLocalStore(LazyReturnTemp); } HandleReturn(); } else { if (expressionOpt != null) { // Ensure the return type has been translated. (Necessary // for cases of untranslated anonymous types.) _module.Translate(expressionOpt.Type, boundReturnStatement.Syntax, _diagnostics); } _builder.EmitRet(expressionOpt == null); } } } private void EmitTryStatement(BoundTryStatement statement, bool emitCatchesOnly = false) { Debug.Assert(!statement.CatchBlocks.IsDefault); // Stack must be empty at beginning of try block. _builder.AssertStackEmpty(); // IL requires catches and finally block to be distinct try // blocks so if the source contained both a catch and // a finally, nested scopes are emitted. bool emitNestedScopes = (!emitCatchesOnly && (statement.CatchBlocks.Length > 0) && (statement.FinallyBlockOpt != null)); _builder.OpenLocalScope(ScopeType.TryCatchFinally); _builder.OpenLocalScope(ScopeType.Try); // IL requires catches and finally block to be distinct try // blocks so if the source contained both a catch and // a finally, nested scopes are emitted. _tryNestingLevel++; if (emitNestedScopes) { EmitTryStatement(statement, emitCatchesOnly: true); } else { EmitBlock(statement.TryBlock); } _tryNestingLevel--; // Close the Try scope _builder.CloseLocalScope(); if (!emitNestedScopes) { foreach (var catchBlock in statement.CatchBlocks) { EmitCatchBlock(catchBlock); } } if (!emitCatchesOnly && (statement.FinallyBlockOpt != null)) { _builder.OpenLocalScope(statement.PreferFaultHandler ? ScopeType.Fault : ScopeType.Finally); EmitBlock(statement.FinallyBlockOpt); // close Finally scope _builder.CloseLocalScope(); // close the whole try statement scope _builder.CloseLocalScope(); // in a case where we emit surrogate Finally using Fault, we emit code like this // // try{ // . . . // } fault { // finallyBlock; // } // finallyBlock; // // This is where the second copy of finallyBlock is emitted. if (statement.PreferFaultHandler) { var finallyClone = FinallyCloner.MakeFinallyClone(statement); EmitBlock(finallyClone); } } else { // close the whole try statement scope _builder.CloseLocalScope(); } } /// <remarks> /// The interesting part in the following method is the support for exception filters. /// === Example: /// /// try /// { /// TryBlock /// } /// catch (ExceptionType ex) when (Condition) /// { /// Handler /// } /// /// gets emitted as something like ===> /// /// Try /// TryBlock /// Filter /// var tmp = Pop() as {ExceptionType} /// if (tmp == null) /// { /// Push 0 /// } /// else /// { /// ex = tmp /// Push Condition ? 1 : 0 /// } /// End Filter // leaves 1 or 0 on the stack /// Catch // gets called after finalization of nested exception frames if condition above produced 1 /// Pop // CLR pushes the exception object again /// variable ex can be used here /// Handler /// EndCatch /// /// When evaluating `Condition` requires additional statements be executed first, those /// statements are stored in `catchBlock.ExceptionFilterPrologueOpt` and emitted before the condition. /// </remarks> private void EmitCatchBlock(BoundCatchBlock catchBlock) { object typeCheckFailedLabel = null; _builder.AdjustStack(1); // Account for exception on the stack. // Open appropriate exception handler scope. (Catch or Filter) // if it is a Filter, emit prologue that checks if the type on the stack // converts to what we want. if (catchBlock.ExceptionFilterOpt == null) { var exceptionType = ((object)catchBlock.ExceptionTypeOpt != null) ? _module.Translate(catchBlock.ExceptionTypeOpt, catchBlock.Syntax, _diagnostics) : _module.GetSpecialType(SpecialType.System_Object, catchBlock.Syntax, _diagnostics); _builder.OpenLocalScope(ScopeType.Catch, exceptionType); RecordAsyncCatchHandlerOffset(catchBlock); // Dev12 inserts the sequence point on catch clause without a filter, just before // the exception object is assigned to the variable. // // Also in Dev12 the exception variable scope span starts right after the stloc instruction and // ends right before leave instruction. So when stopped at the sequence point Dev12 inserts, // the exception variable is not visible. if (_emitPdbSequencePoints) { var syntax = catchBlock.Syntax as CatchClauseSyntax; if (syntax != null) { TextSpan spSpan; var declaration = syntax.Declaration; if (declaration == null) { spSpan = syntax.CatchKeyword.Span; } else { spSpan = TextSpan.FromBounds(syntax.SpanStart, syntax.Declaration.Span.End); } this.EmitSequencePoint(catchBlock.SyntaxTree, spSpan); } } } else { _builder.OpenLocalScope(ScopeType.Filter); RecordAsyncCatchHandlerOffset(catchBlock); // Filtering starts with simulating regular catch through a // type check. If this is not our type then we are done. var typeCheckPassedLabel = new object(); typeCheckFailedLabel = new object(); if ((object)catchBlock.ExceptionTypeOpt != null) { var exceptionType = _module.Translate(catchBlock.ExceptionTypeOpt, catchBlock.Syntax, _diagnostics); _builder.EmitOpCode(ILOpCode.Isinst); _builder.EmitToken(exceptionType, catchBlock.Syntax, _diagnostics); _builder.EmitOpCode(ILOpCode.Dup); _builder.EmitBranch(ILOpCode.Brtrue, typeCheckPassedLabel); _builder.EmitOpCode(ILOpCode.Pop); _builder.EmitIntConstant(0); _builder.EmitBranch(ILOpCode.Br, typeCheckFailedLabel); } else { // no formal exception type means we always pass the check } _builder.MarkLabel(typeCheckPassedLabel); } foreach (var local in catchBlock.Locals) { var declaringReferences = local.DeclaringSyntaxReferences; var localSyntax = !declaringReferences.IsEmpty ? (CSharpSyntaxNode)declaringReferences[0].GetSyntax() : catchBlock.Syntax; DefineLocal(local, localSyntax); } var exceptionSourceOpt = catchBlock.ExceptionSourceOpt; if (exceptionSourceOpt != null) { // here we have our exception on the stack in a form of a reference type (O) // it means that we have to "unbox" it before storing to the local // if exception's type is a generic type parameter. if (!exceptionSourceOpt.Type.IsVerifierReference()) { Debug.Assert(exceptionSourceOpt.Type.IsTypeParameter()); // only expecting type parameters _builder.EmitOpCode(ILOpCode.Unbox_any); EmitSymbolToken(exceptionSourceOpt.Type, exceptionSourceOpt.Syntax); } BoundExpression exceptionSource = exceptionSourceOpt; while (exceptionSource.Kind == BoundKind.Sequence) { var seq = (BoundSequence)exceptionSource; Debug.Assert(seq.Locals.IsDefaultOrEmpty); EmitSideEffects(seq); exceptionSource = seq.Value; } switch (exceptionSource.Kind) { case BoundKind.Local: var exceptionSourceLocal = (BoundLocal)exceptionSource; Debug.Assert(exceptionSourceLocal.LocalSymbol.RefKind == RefKind.None); if (!IsStackLocal(exceptionSourceLocal.LocalSymbol)) { _builder.EmitLocalStore(GetLocal(exceptionSourceLocal)); } break; case BoundKind.FieldAccess: var left = (BoundFieldAccess)exceptionSource; Debug.Assert(!left.FieldSymbol.IsStatic, "Not supported"); Debug.Assert(!left.ReceiverOpt.Type.IsTypeParameter()); var stateMachineField = left.FieldSymbol as StateMachineFieldSymbol; if (((object)stateMachineField != null) && (stateMachineField.SlotIndex >= 0)) { _builder.DefineUserDefinedStateMachineHoistedLocal(stateMachineField.SlotIndex); } // When assigning to a field // we need to push param address below the exception var temp = AllocateTemp(exceptionSource.Type, exceptionSource.Syntax); _builder.EmitLocalStore(temp); var receiverTemp = EmitReceiverRef(left.ReceiverOpt, AddressKind.Writeable); Debug.Assert(receiverTemp == null); _builder.EmitLocalLoad(temp); FreeTemp(temp); EmitFieldStore(left); break; default: throw ExceptionUtilities.UnexpectedValue(exceptionSource.Kind); } } else { _builder.EmitOpCode(ILOpCode.Pop); } if (catchBlock.ExceptionFilterPrologueOpt != null) { Debug.Assert(_builder.IsStackEmpty); EmitStatements(catchBlock.ExceptionFilterPrologueOpt.Statements); } // Emit the actual filter expression, if we have one, and normalize // results. if (catchBlock.ExceptionFilterOpt != null) { EmitCondExpr(catchBlock.ExceptionFilterOpt, true); // Normalize the return value because values other than 0 or 1 // produce unspecified results. _builder.EmitIntConstant(0); _builder.EmitOpCode(ILOpCode.Cgt_un); _builder.MarkLabel(typeCheckFailedLabel); // Now we are starting the actual handler _builder.MarkFilterConditionEnd(); // Pop the exception; it should have already been stored to the // variable by the filter. _builder.EmitOpCode(ILOpCode.Pop); } EmitBlock(catchBlock.Body); _builder.CloseLocalScope(); } private void RecordAsyncCatchHandlerOffset(BoundCatchBlock catchBlock) { if (catchBlock.IsSynthesizedAsyncCatchAll) { Debug.Assert(_asyncCatchHandlerOffset < 0); // only one expected _asyncCatchHandlerOffset = _builder.AllocateILMarker(); } } private void EmitSwitchDispatch(BoundSwitchDispatch dispatch) { // Switch expression must have a valid switch governing type Debug.Assert((object)dispatch.Expression.Type != null); Debug.Assert(dispatch.Expression.Type.IsValidV6SwitchGoverningType()); // We must have rewritten nullable switch expression into non-nullable constructs. Debug.Assert(!dispatch.Expression.Type.IsNullableType()); // This must be used only for nontrivial dispatches. Debug.Assert(dispatch.Cases.Any()); EmitSwitchHeader( dispatch.Expression, dispatch.Cases.Select(p => new KeyValuePair<ConstantValue, object>(p.value, p.label)).ToArray(), dispatch.DefaultLabel, dispatch.EqualityMethod); } private void EmitSwitchHeader( BoundExpression expression, KeyValuePair<ConstantValue, object>[] switchCaseLabels, LabelSymbol fallThroughLabel, MethodSymbol equalityMethod) { Debug.Assert(expression.ConstantValue == null); Debug.Assert((object)expression.Type != null && expression.Type.IsValidV6SwitchGoverningType()); Debug.Assert(switchCaseLabels.Length > 0); Debug.Assert(switchCaseLabels != null); LocalDefinition temp = null; LocalOrParameter key; BoundSequence sequence = null; if (expression.Kind == BoundKind.Sequence) { sequence = (BoundSequence)expression; DefineLocals(sequence); EmitSideEffects(sequence); expression = sequence.Value; } if (expression.Kind == BoundKind.SequencePointExpression) { var sequencePointExpression = (BoundSequencePointExpression)expression; EmitSequencePoint(sequencePointExpression); expression = sequencePointExpression.Expression; } switch (expression.Kind) { case BoundKind.Local: var local = ((BoundLocal)expression).LocalSymbol; if (local.RefKind == RefKind.None && !IsStackLocal(local)) { key = this.GetLocal(local); break; } goto default; case BoundKind.Parameter: var parameter = (BoundParameter)expression; if (parameter.ParameterSymbol.RefKind == RefKind.None) { key = ParameterSlot(parameter); break; } goto default; default: EmitExpression(expression, true); temp = AllocateTemp(expression.Type, expression.Syntax); _builder.EmitLocalStore(temp); key = temp; break; } // Emit switch jump table if (expression.Type.SpecialType != SpecialType.System_String) { _builder.EmitIntegerSwitchJumpTable(switchCaseLabels, fallThroughLabel, key, expression.Type.EnumUnderlyingTypeOrSelf().PrimitiveTypeCode); } else { this.EmitStringSwitchJumpTable(switchCaseLabels, fallThroughLabel, key, expression.Syntax, equalityMethod); } if (temp != null) { FreeTemp(temp); } if (sequence != null) { // sequence was used as a value, can release all its locals. FreeLocals(sequence); } } private void EmitStringSwitchJumpTable( KeyValuePair<ConstantValue, object>[] switchCaseLabels, LabelSymbol fallThroughLabel, LocalOrParameter key, SyntaxNode syntaxNode, MethodSymbol equalityMethod) { LocalDefinition keyHash = null; // Condition is necessary, but not sufficient (e.g. might be missing a special or well-known member). if (SwitchStringJumpTableEmitter.ShouldGenerateHashTableSwitch(_module, switchCaseLabels.Length)) { Debug.Assert(_module.SupportsPrivateImplClass); var privateImplClass = _module.GetPrivateImplClass(syntaxNode, _diagnostics); Cci.IReference stringHashMethodRef = privateImplClass.GetMethod(PrivateImplementationDetails.SynthesizedStringHashFunctionName); // Heuristics and well-known member availability determine the existence // of this helper. Rather than reproduce that (language-specific) logic here, // we simply check for the information we really want - whether the helper is // available. if (stringHashMethodRef != null) { // static uint ComputeStringHash(string s) // pop 1 (s) // push 1 (uint return value) // stackAdjustment = (pushCount - popCount) = 0 _builder.EmitLoad(key); _builder.EmitOpCode(ILOpCode.Call, stackAdjustment: 0); _builder.EmitToken(stringHashMethodRef, syntaxNode, _diagnostics); var UInt32Type = _module.Compilation.GetSpecialType(SpecialType.System_UInt32); keyHash = AllocateTemp(UInt32Type, syntaxNode); _builder.EmitLocalStore(keyHash); } } Cci.IReference stringEqualityMethodRef = _module.Translate(equalityMethod, syntaxNode, _diagnostics); Cci.IMethodReference stringLengthRef = null; var stringLengthMethod = _module.Compilation.GetSpecialTypeMember(SpecialMember.System_String__Length) as MethodSymbol; if (stringLengthMethod != null && !stringLengthMethod.HasUseSiteError) { stringLengthRef = _module.Translate(stringLengthMethod, syntaxNode, _diagnostics); } SwitchStringJumpTableEmitter.EmitStringCompareAndBranch emitStringCondBranchDelegate = (keyArg, stringConstant, targetLabel) => { if (stringConstant == ConstantValue.Null) { // if (key == null) // goto targetLabel _builder.EmitLoad(keyArg); _builder.EmitBranch(ILOpCode.Brfalse, targetLabel, ILOpCode.Brtrue); } else if (stringConstant.StringValue.Length == 0 && stringLengthRef != null) { // if (key != null && key.Length == 0) // goto targetLabel object skipToNext = new object(); _builder.EmitLoad(keyArg); _builder.EmitBranch(ILOpCode.Brfalse, skipToNext, ILOpCode.Brtrue); _builder.EmitLoad(keyArg); // Stack: key --> length _builder.EmitOpCode(ILOpCode.Call, 0); var diag = DiagnosticBag.GetInstance(); _builder.EmitToken(stringLengthRef, null, diag); Debug.Assert(diag.IsEmptyWithoutResolution); diag.Free(); _builder.EmitBranch(ILOpCode.Brfalse, targetLabel, ILOpCode.Brtrue); _builder.MarkLabel(skipToNext); } else { this.EmitStringCompareAndBranch(key, syntaxNode, stringConstant, targetLabel, stringEqualityMethodRef); } }; _builder.EmitStringSwitchJumpTable( caseLabels: switchCaseLabels, fallThroughLabel: fallThroughLabel, key: key, keyHash: keyHash, emitStringCondBranchDelegate: emitStringCondBranchDelegate, computeStringHashcodeDelegate: SynthesizedStringSwitchHashMethod.ComputeStringHash); if (keyHash != null) { FreeTemp(keyHash); } } /// <summary> /// Delegate to emit string compare call and conditional branch based on the compare result. /// </summary> /// <param name="key">Key to compare</param> /// <param name="syntaxNode">Node for diagnostics.</param> /// <param name="stringConstant">Case constant to compare the key against</param> /// <param name="targetLabel">Target label to branch to if key = stringConstant</param> /// <param name="stringEqualityMethodRef">String equality method</param> private void EmitStringCompareAndBranch(LocalOrParameter key, SyntaxNode syntaxNode, ConstantValue stringConstant, object targetLabel, Microsoft.Cci.IReference stringEqualityMethodRef) { // Emit compare and branch: // if (key == stringConstant) // goto targetLabel; Debug.Assert(stringEqualityMethodRef != null); #if DEBUG var assertDiagnostics = DiagnosticBag.GetInstance(); Debug.Assert(stringEqualityMethodRef == _module.Translate((MethodSymbol)_module.Compilation.GetSpecialTypeMember(SpecialMember.System_String__op_Equality), (CSharpSyntaxNode)syntaxNode, assertDiagnostics)); assertDiagnostics.Free(); #endif // static bool String.Equals(string a, string b) // pop 2 (a, b) // push 1 (bool return value) // stackAdjustment = (pushCount - popCount) = -1 _builder.EmitLoad(key); _builder.EmitConstantValue(stringConstant); _builder.EmitOpCode(ILOpCode.Call, stackAdjustment: -1); _builder.EmitToken(stringEqualityMethodRef, syntaxNode, _diagnostics); // Branch to targetLabel if String.Equals returned true. _builder.EmitBranch(ILOpCode.Brtrue, targetLabel, ILOpCode.Brfalse); } /// <summary> /// Gets already declared and initialized local. /// </summary> private LocalDefinition GetLocal(BoundLocal localExpression) { var symbol = localExpression.LocalSymbol; return GetLocal(symbol); } private LocalDefinition GetLocal(LocalSymbol symbol) { return _builder.LocalSlotManager.GetLocal(symbol); } private LocalDefinition DefineLocal(LocalSymbol local, SyntaxNode syntaxNode) { var dynamicTransformFlags = !local.IsCompilerGenerated && local.Type.ContainsDynamic() ? CSharpCompilation.DynamicTransformsEncoder.Encode(local.Type, RefKind.None, 0) : ImmutableArray<bool>.Empty; var tupleElementNames = !local.IsCompilerGenerated && local.Type.ContainsTupleNames() ? CSharpCompilation.TupleNamesEncoder.Encode(local.Type) : ImmutableArray<string>.Empty; if (local.IsConst) { Debug.Assert(local.HasConstantValue); MetadataConstant compileTimeValue = _module.CreateConstant(local.Type, local.ConstantValue, syntaxNode, _diagnostics); LocalConstantDefinition localConstantDef = new LocalConstantDefinition( local.Name, local.Locations.FirstOrDefault() ?? Location.None, compileTimeValue, dynamicTransformFlags: dynamicTransformFlags, tupleElementNames: tupleElementNames); _builder.AddLocalConstantToScope(localConstantDef); return null; } if (IsStackLocal(local)) { return null; } LocalSlotConstraints constraints; Cci.ITypeReference translatedType; if (local.DeclarationKind == LocalDeclarationKind.FixedVariable && local.IsPinned) // Excludes pointer local and string local in fixed string case. { Debug.Assert(local.RefKind == RefKind.None); Debug.Assert(local.TypeWithAnnotations.Type.IsPointerType()); constraints = LocalSlotConstraints.ByRef | LocalSlotConstraints.Pinned; PointerTypeSymbol pointerType = (PointerTypeSymbol)local.Type; TypeSymbol pointedAtType = pointerType.PointedAtType; // We can't declare a reference to void, so if the pointed-at type is void, use native int // (represented here by IntPtr) instead. translatedType = pointedAtType.IsVoidType() ? _module.GetSpecialType(SpecialType.System_IntPtr, syntaxNode, _diagnostics) : _module.Translate(pointedAtType, syntaxNode, _diagnostics); } else { constraints = (local.IsPinned ? LocalSlotConstraints.Pinned : LocalSlotConstraints.None) | (local.RefKind != RefKind.None ? LocalSlotConstraints.ByRef : LocalSlotConstraints.None); translatedType = _module.Translate(local.Type, syntaxNode, _diagnostics); } // Even though we don't need the token immediately, we will need it later when signature for the local is emitted. // Also, requesting the token has side-effect of registering types used, which is critical for embedded types (NoPia, VBCore, etc). _module.GetFakeSymbolTokenForIL(translatedType, syntaxNode, _diagnostics); LocalDebugId localId; var name = GetLocalDebugName(local, out localId); var localDef = _builder.LocalSlotManager.DeclareLocal( type: translatedType, symbol: local, name: name, kind: local.SynthesizedKind, id: localId, pdbAttributes: local.SynthesizedKind.PdbAttributes(), constraints: constraints, dynamicTransformFlags: dynamicTransformFlags, tupleElementNames: tupleElementNames, isSlotReusable: local.SynthesizedKind.IsSlotReusable(_ilEmitStyle != ILEmitStyle.Release)); // If named, add it to the local debug scope. if (localDef.Name != null && !(local.SynthesizedKind == SynthesizedLocalKind.UserDefined && // Visibility scope of such locals is represented by BoundScope node. (local.ScopeDesignatorOpt?.Kind() is SyntaxKind.SwitchSection or SyntaxKind.SwitchExpressionArm))) { _builder.AddLocalToScope(localDef); } return localDef; } /// <summary> /// Gets the name and id of the local that are going to be generated into the debug metadata. /// </summary> private string GetLocalDebugName(ILocalSymbolInternal local, out LocalDebugId localId) { localId = LocalDebugId.None; if (local.IsImportedFromMetadata) { return local.Name; } var localKind = local.SynthesizedKind; // only user-defined locals should be named during lowering: Debug.Assert((local.Name == null) == (localKind != SynthesizedLocalKind.UserDefined)); // Generating debug names for instrumentation payloads should be allowed, as described in https://github.com/dotnet/roslyn/issues/11024. // For now, skip naming locals generated by instrumentation as they might not have a local syntax offset. // Locals generated by instrumentation might exist in methods which do not contain a body (auto property initializers). if (!localKind.IsLongLived() || localKind == SynthesizedLocalKind.InstrumentationPayload) { return null; } if (_ilEmitStyle == ILEmitStyle.Debug) { var syntax = local.GetDeclaratorSyntax(); int syntaxOffset = _method.CalculateLocalSyntaxOffset(LambdaUtilities.GetDeclaratorPosition(syntax), syntax.SyntaxTree); int ordinal = _synthesizedLocalOrdinals.AssignLocalOrdinal(localKind, syntaxOffset); // user-defined locals should have 0 ordinal: Debug.Assert(ordinal == 0 || localKind != SynthesizedLocalKind.UserDefined); localId = new LocalDebugId(syntaxOffset, ordinal); } return local.Name ?? GeneratedNames.MakeSynthesizedLocalName(localKind, ref _uniqueNameId); } private bool IsSlotReusable(LocalSymbol local) { return local.SynthesizedKind.IsSlotReusable(_ilEmitStyle != ILEmitStyle.Release); } /// <summary> /// Releases a local. /// </summary> private void FreeLocal(LocalSymbol local) { // TODO: releasing named locals is NYI. if (local.Name == null && IsSlotReusable(local) && !IsStackLocal(local)) { _builder.LocalSlotManager.FreeLocal(local); } } /// <summary> /// Allocates a temp without identity. /// </summary> private LocalDefinition AllocateTemp(TypeSymbol type, SyntaxNode syntaxNode, LocalSlotConstraints slotConstraints = LocalSlotConstraints.None) { return _builder.LocalSlotManager.AllocateSlot( _module.Translate(type, syntaxNode, _diagnostics), slotConstraints); } /// <summary> /// Frees a temp. /// </summary> private void FreeTemp(LocalDefinition temp) { _builder.LocalSlotManager.FreeSlot(temp); } /// <summary> /// Frees an optional temp. /// </summary> private void FreeOptTemp(LocalDefinition temp) { if (temp != null) { FreeTemp(temp); } } /// <summary> /// Clones all labels used in a finally block. /// This allows creating an emittable clone of finally. /// It is safe to do because no branches can go in or out of the finally handler. /// </summary> private class FinallyCloner : BoundTreeRewriterWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator { private Dictionary<LabelSymbol, GeneratedLabelSymbol> _labelClones; private FinallyCloner() { } /// <summary> /// The argument is BoundTryStatement (and not a BoundBlock) specifically /// to support only Finally blocks where it is guaranteed to not have incoming or leaving branches. /// </summary> public static BoundBlock MakeFinallyClone(BoundTryStatement node) { var cloner = new FinallyCloner(); return (BoundBlock)cloner.Visit(node.FinallyBlockOpt); } public override BoundNode VisitLabelStatement(BoundLabelStatement node) { return node.Update(GetLabelClone(node.Label)); } public override BoundNode VisitGotoStatement(BoundGotoStatement node) { var labelClone = GetLabelClone(node.Label); // expressions do not contain labels or branches BoundExpression caseExpressionOpt = node.CaseExpressionOpt; // expressions do not contain labels or branches BoundLabel labelExpressionOpt = node.LabelExpressionOpt; return node.Update(labelClone, caseExpressionOpt, labelExpressionOpt); } public override BoundNode VisitConditionalGoto(BoundConditionalGoto node) { var labelClone = GetLabelClone(node.Label); // expressions do not contain labels or branches BoundExpression condition = node.Condition; return node.Update(condition, node.JumpIfTrue, labelClone); } public override BoundNode VisitSwitchDispatch(BoundSwitchDispatch node) { // expressions do not contain labels or branches BoundExpression expression = node.Expression; var defaultClone = GetLabelClone(node.DefaultLabel); var casesBuilder = ArrayBuilder<(ConstantValue, LabelSymbol)>.GetInstance(); foreach (var (value, label) in node.Cases) { casesBuilder.Add((value, GetLabelClone(label))); } return node.Update(expression, casesBuilder.ToImmutableAndFree(), defaultClone, node.EqualityMethod); } public override BoundNode VisitExpressionStatement(BoundExpressionStatement node) { // expressions do not contain labels or branches return node; } private GeneratedLabelSymbol GetLabelClone(LabelSymbol label) { var labelClones = _labelClones; if (labelClones == null) { _labelClones = labelClones = new Dictionary<LabelSymbol, GeneratedLabelSymbol>(); } GeneratedLabelSymbol clone; if (!labelClones.TryGetValue(label, out clone)) { clone = new GeneratedLabelSymbol("cloned_" + label.Name); labelClones.Add(label, clone); } return clone; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection.Metadata; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CSharp.Binder; namespace Microsoft.CodeAnalysis.CSharp.CodeGen { internal partial class CodeGenerator { private void EmitStatement(BoundStatement statement) { switch (statement.Kind) { case BoundKind.Block: EmitBlock((BoundBlock)statement); break; case BoundKind.Scope: EmitScope((BoundScope)statement); break; case BoundKind.SequencePoint: this.EmitSequencePointStatement((BoundSequencePoint)statement); break; case BoundKind.SequencePointWithSpan: this.EmitSequencePointStatement((BoundSequencePointWithSpan)statement); break; case BoundKind.SavePreviousSequencePoint: this.EmitSavePreviousSequencePoint((BoundSavePreviousSequencePoint)statement); break; case BoundKind.RestorePreviousSequencePoint: this.EmitRestorePreviousSequencePoint((BoundRestorePreviousSequencePoint)statement); break; case BoundKind.StepThroughSequencePoint: this.EmitStepThroughSequencePoint((BoundStepThroughSequencePoint)statement); break; case BoundKind.ExpressionStatement: EmitExpression(((BoundExpressionStatement)statement).Expression, false); break; case BoundKind.StatementList: EmitStatementList((BoundStatementList)statement); break; case BoundKind.ReturnStatement: EmitReturnStatement((BoundReturnStatement)statement); break; case BoundKind.GotoStatement: EmitGotoStatement((BoundGotoStatement)statement); break; case BoundKind.LabelStatement: EmitLabelStatement((BoundLabelStatement)statement); break; case BoundKind.ConditionalGoto: EmitConditionalGoto((BoundConditionalGoto)statement); break; case BoundKind.ThrowStatement: EmitThrowStatement((BoundThrowStatement)statement); break; case BoundKind.TryStatement: EmitTryStatement((BoundTryStatement)statement); break; case BoundKind.SwitchDispatch: EmitSwitchDispatch((BoundSwitchDispatch)statement); break; case BoundKind.StateMachineScope: EmitStateMachineScope((BoundStateMachineScope)statement); break; case BoundKind.NoOpStatement: EmitNoOpStatement((BoundNoOpStatement)statement); break; default: // Code gen should not be invoked if there are errors. throw ExceptionUtilities.UnexpectedValue(statement.Kind); } #if DEBUG if (_stackLocals == null || _stackLocals.Count == 0) { _builder.AssertStackEmpty(); } #endif ReleaseExpressionTemps(); } private int EmitStatementAndCountInstructions(BoundStatement statement) { int n = _builder.InstructionsEmitted; this.EmitStatement(statement); return _builder.InstructionsEmitted - n; } private void EmitStatementList(BoundStatementList list) { for (int i = 0, n = list.Statements.Length; i < n; i++) { EmitStatement(list.Statements[i]); } } private void EmitNoOpStatement(BoundNoOpStatement statement) { switch (statement.Flavor) { case NoOpStatementFlavor.Default: if (_ilEmitStyle == ILEmitStyle.Debug) { _builder.EmitOpCode(ILOpCode.Nop); } break; case NoOpStatementFlavor.AwaitYieldPoint: Debug.Assert((_asyncYieldPoints == null) == (_asyncResumePoints == null)); if (_asyncYieldPoints == null) { _asyncYieldPoints = ArrayBuilder<int>.GetInstance(); _asyncResumePoints = ArrayBuilder<int>.GetInstance(); } Debug.Assert(_asyncYieldPoints.Count == _asyncResumePoints.Count); _asyncYieldPoints.Add(_builder.AllocateILMarker()); break; case NoOpStatementFlavor.AwaitResumePoint: Debug.Assert(_asyncYieldPoints != null); Debug.Assert(_asyncYieldPoints != null); _asyncResumePoints.Add(_builder.AllocateILMarker()); Debug.Assert(_asyncYieldPoints.Count == _asyncResumePoints.Count); break; default: throw ExceptionUtilities.UnexpectedValue(statement.Flavor); } } private void EmitThrowStatement(BoundThrowStatement node) { EmitThrow(node.ExpressionOpt); } private void EmitThrow(BoundExpression thrown) { if (thrown != null) { this.EmitExpression(thrown, true); var exprType = thrown.Type; // Expression type will be null for "throw null;". if (exprType?.TypeKind == TypeKind.TypeParameter) { this.EmitBox(exprType, thrown.Syntax); } } _builder.EmitThrow(isRethrow: thrown == null); } private void EmitConditionalGoto(BoundConditionalGoto boundConditionalGoto) { object label = boundConditionalGoto.Label; Debug.Assert(label != null); EmitCondBranch(boundConditionalGoto.Condition, ref label, boundConditionalGoto.JumpIfTrue); } // 3.17 The brfalse instruction transfers control to target if value (of type int32, int64, object reference, managed //pointer, unmanaged pointer or native int) is zero (false). If value is non-zero (true), execution continues at //the next instruction. private static bool CanPassToBrfalse(TypeSymbol ts) { if (ts.IsEnumType()) { // valid enums are all primitives return true; } var tc = ts.PrimitiveTypeCode; switch (tc) { case Microsoft.Cci.PrimitiveTypeCode.Float32: case Microsoft.Cci.PrimitiveTypeCode.Float64: return false; case Microsoft.Cci.PrimitiveTypeCode.NotPrimitive: // if this is a generic type param, verifier will want us to box // EmitCondBranch knows that return ts.IsReferenceType; default: Debug.Assert(tc != Microsoft.Cci.PrimitiveTypeCode.Invalid); Debug.Assert(tc != Microsoft.Cci.PrimitiveTypeCode.Void); return true; } } private static BoundExpression TryReduce(BoundBinaryOperator condition, ref bool sense) { var opKind = condition.OperatorKind.Operator(); Debug.Assert(opKind == BinaryOperatorKind.Equal || opKind == BinaryOperatorKind.NotEqual); BoundExpression nonConstOp; BoundExpression constOp = (condition.Left.ConstantValue != null) ? condition.Left : null; if (constOp != null) { nonConstOp = condition.Right; } else { constOp = (condition.Right.ConstantValue != null) ? condition.Right : null; if (constOp == null) { return null; } nonConstOp = condition.Left; } var nonConstType = nonConstOp.Type; if (!CanPassToBrfalse(nonConstType)) { return null; } bool isBool = nonConstType.PrimitiveTypeCode == Microsoft.Cci.PrimitiveTypeCode.Boolean; bool isZero = constOp.ConstantValue.IsDefaultValue; // bool is special, only it can be compared to true and false... if (!isBool && !isZero) { return null; } // if comparing to zero, flip the sense if (isZero) { sense = !sense; } // if comparing != flip the sense if (opKind == BinaryOperatorKind.NotEqual) { sense = !sense; } return nonConstOp; } private const int IL_OP_CODE_ROW_LENGTH = 4; private static readonly ILOpCode[] s_condJumpOpCodes = new ILOpCode[] { // < <= > >= ILOpCode.Blt, ILOpCode.Ble, ILOpCode.Bgt, ILOpCode.Bge, // Signed ILOpCode.Bge, ILOpCode.Bgt, ILOpCode.Ble, ILOpCode.Blt, // Signed Invert ILOpCode.Blt_un, ILOpCode.Ble_un, ILOpCode.Bgt_un, ILOpCode.Bge_un, // Unsigned ILOpCode.Bge_un, ILOpCode.Bgt_un, ILOpCode.Ble_un, ILOpCode.Blt_un, // Unsigned Invert ILOpCode.Blt, ILOpCode.Ble, ILOpCode.Bgt, ILOpCode.Bge, // Float ILOpCode.Bge_un, ILOpCode.Bgt_un, ILOpCode.Ble_un, ILOpCode.Blt_un, // Float Invert }; /// <summary> /// Produces opcode for a jump that corresponds to given operation and sense. /// Also produces a reverse opcode - opcode for the same condition with inverted sense. /// </summary> private static ILOpCode CodeForJump(BoundBinaryOperator op, bool sense, out ILOpCode revOpCode) { int opIdx; switch (op.OperatorKind.Operator()) { case BinaryOperatorKind.Equal: revOpCode = !sense ? ILOpCode.Beq : ILOpCode.Bne_un; return sense ? ILOpCode.Beq : ILOpCode.Bne_un; case BinaryOperatorKind.NotEqual: revOpCode = !sense ? ILOpCode.Bne_un : ILOpCode.Beq; return sense ? ILOpCode.Bne_un : ILOpCode.Beq; case BinaryOperatorKind.LessThan: opIdx = 0; break; case BinaryOperatorKind.LessThanOrEqual: opIdx = 1; break; case BinaryOperatorKind.GreaterThan: opIdx = 2; break; case BinaryOperatorKind.GreaterThanOrEqual: opIdx = 3; break; default: throw ExceptionUtilities.UnexpectedValue(op.OperatorKind.Operator()); } if (IsUnsignedBinaryOperator(op)) { opIdx += 2 * IL_OP_CODE_ROW_LENGTH; //unsigned } else if (IsFloat(op.OperatorKind)) { opIdx += 4 * IL_OP_CODE_ROW_LENGTH; //float } int revOpIdx = opIdx; if (!sense) { opIdx += IL_OP_CODE_ROW_LENGTH; //invert op } else { revOpIdx += IL_OP_CODE_ROW_LENGTH; //invert rev } revOpCode = s_condJumpOpCodes[revOpIdx]; return s_condJumpOpCodes[opIdx]; } // generate a jump to dest if (condition == sense) is true private void EmitCondBranch(BoundExpression condition, ref object dest, bool sense) { _recursionDepth++; if (_recursionDepth > 1) { StackGuard.EnsureSufficientExecutionStack(_recursionDepth); EmitCondBranchCore(condition, ref dest, sense); } else { EmitCondBranchCoreWithStackGuard(condition, ref dest, sense); } _recursionDepth--; } private void EmitCondBranchCoreWithStackGuard(BoundExpression condition, ref object dest, bool sense) { Debug.Assert(_recursionDepth == 1); try { EmitCondBranchCore(condition, ref dest, sense); Debug.Assert(_recursionDepth == 1); } catch (InsufficientExecutionStackException) { _diagnostics.Add(ErrorCode.ERR_InsufficientStack, BoundTreeVisitor.CancelledByStackGuardException.GetTooLongOrComplexExpressionErrorLocation(condition)); throw new EmitCancelledException(); } } private void EmitCondBranchCore(BoundExpression condition, ref object dest, bool sense) { oneMoreTime: ILOpCode ilcode; if (condition.ConstantValue != null) { bool taken = condition.ConstantValue.IsDefaultValue != sense; if (taken) { dest = dest ?? new object(); _builder.EmitBranch(ILOpCode.Br, dest); } else { // otherwise this branch will never be taken, so just fall through... } return; } switch (condition.Kind) { case BoundKind.BinaryOperator: var binOp = (BoundBinaryOperator)condition; bool testBothArgs = sense; switch (binOp.OperatorKind.OperatorWithLogical()) { case BinaryOperatorKind.LogicalOr: testBothArgs = !testBothArgs; // Fall through goto case BinaryOperatorKind.LogicalAnd; case BinaryOperatorKind.LogicalAnd: if (testBothArgs) { // gotoif(a != sense) fallThrough // gotoif(b == sense) dest // fallThrough: object fallThrough = null; EmitCondBranch(binOp.Left, ref fallThrough, !sense); EmitCondBranch(binOp.Right, ref dest, sense); if (fallThrough != null) { _builder.MarkLabel(fallThrough); } } else { // gotoif(a == sense) labDest // gotoif(b == sense) labDest EmitCondBranch(binOp.Left, ref dest, sense); condition = binOp.Right; goto oneMoreTime; } return; case BinaryOperatorKind.Equal: case BinaryOperatorKind.NotEqual: var reduced = TryReduce(binOp, ref sense); if (reduced != null) { condition = reduced; goto oneMoreTime; } // Fall through goto case BinaryOperatorKind.LessThan; case BinaryOperatorKind.LessThan: case BinaryOperatorKind.LessThanOrEqual: case BinaryOperatorKind.GreaterThan: case BinaryOperatorKind.GreaterThanOrEqual: EmitExpression(binOp.Left, true); EmitExpression(binOp.Right, true); ILOpCode revOpCode; ilcode = CodeForJump(binOp, sense, out revOpCode); dest = dest ?? new object(); _builder.EmitBranch(ilcode, dest, revOpCode); return; } // none of above. // then it is regular binary expression - Or, And, Xor ... goto default; case BoundKind.LoweredConditionalAccess: { var ca = (BoundLoweredConditionalAccess)condition; var receiver = ca.Receiver; var receiverType = receiver.Type; // we need a copy if we deal with nonlocal value (to capture the value) // or if we deal with stack local (reads are destructive) var complexCase = !receiverType.IsReferenceType || LocalRewriter.CanChangeValueBetweenReads(receiver, localsMayBeAssignedOrCaptured: false) || (receiver.Kind == BoundKind.Local && IsStackLocal(((BoundLocal)receiver).LocalSymbol)) || (ca.WhenNullOpt?.IsDefaultValue() == false); if (complexCase) { goto default; } if (sense) { // gotoif(receiver != null) fallThrough // gotoif(receiver.Access) dest // fallThrough: object fallThrough = null; EmitCondBranch(receiver, ref fallThrough, sense: false); // receiver is a reference type, and we only intend to read it EmitReceiverRef(receiver, AddressKind.ReadOnly); EmitCondBranch(ca.WhenNotNull, ref dest, sense: true); if (fallThrough != null) { _builder.MarkLabel(fallThrough); } } else { // gotoif(receiver == null) labDest // gotoif(!receiver.Access) labDest EmitCondBranch(receiver, ref dest, sense: false); // receiver is a reference type, and we only intend to read it EmitReceiverRef(receiver, AddressKind.ReadOnly); condition = ca.WhenNotNull; goto oneMoreTime; } } return; case BoundKind.UnaryOperator: var unOp = (BoundUnaryOperator)condition; if (unOp.OperatorKind == UnaryOperatorKind.BoolLogicalNegation) { sense = !sense; condition = unOp.Operand; goto oneMoreTime; } goto default; case BoundKind.IsOperator: var isOp = (BoundIsOperator)condition; var operand = isOp.Operand; EmitExpression(operand, true); Debug.Assert((object)operand.Type != null); if (!operand.Type.IsVerifierReference()) { // box the operand for isinst if it is not a verifier reference EmitBox(operand.Type, operand.Syntax); } _builder.EmitOpCode(ILOpCode.Isinst); EmitSymbolToken(isOp.TargetType.Type, isOp.TargetType.Syntax); ilcode = sense ? ILOpCode.Brtrue : ILOpCode.Brfalse; dest = dest ?? new object(); _builder.EmitBranch(ilcode, dest); return; case BoundKind.Sequence: var seq = (BoundSequence)condition; EmitSequenceCondBranch(seq, ref dest, sense); return; default: EmitExpression(condition, true); var conditionType = condition.Type; if (conditionType.IsReferenceType && !conditionType.IsVerifierReference()) { EmitBox(conditionType, condition.Syntax); } ilcode = sense ? ILOpCode.Brtrue : ILOpCode.Brfalse; dest = dest ?? new object(); _builder.EmitBranch(ilcode, dest); return; } } private void EmitSequenceCondBranch(BoundSequence sequence, ref object dest, bool sense) { DefineLocals(sequence); EmitSideEffects(sequence); EmitCondBranch(sequence.Value, ref dest, sense); // sequence is used as a value, can release all locals FreeLocals(sequence); } private void EmitLabelStatement(BoundLabelStatement boundLabelStatement) { _builder.MarkLabel(boundLabelStatement.Label); } private void EmitGotoStatement(BoundGotoStatement boundGotoStatement) { _builder.EmitBranch(ILOpCode.Br, boundGotoStatement.Label); } // used by HandleReturn method which tries to inject // indirect ret sequence as a last statement in the block // that is the last statement of the current method // NOTE: it is important that there is no code after this "ret" // it is desirable, for debug purposes, that this ret is emitted inside top level { } private bool IsLastBlockInMethod(BoundBlock block) { if (_boundBody == block) { return true; } //sometimes top level node is a statement list containing //epilogue and then a block. If we are having that block, it will do. var list = _boundBody as BoundStatementList; if (list != null && list.Statements.LastOrDefault() == block) { return true; } return false; } private void EmitBlock(BoundBlock block) { var hasLocals = !block.Locals.IsEmpty; if (hasLocals) { _builder.OpenLocalScope(); foreach (var local in block.Locals) { Debug.Assert(local.RefKind == RefKind.None || local.SynthesizedKind.IsLongLived(), "A ref local ended up in a block and claims it is shortlived. That is dangerous. Are we sure it is short lived?"); var declaringReferences = local.DeclaringSyntaxReferences; DefineLocal(local, !declaringReferences.IsEmpty ? (CSharpSyntaxNode)declaringReferences[0].GetSyntax() : block.Syntax); } } EmitStatements(block.Statements); if (_indirectReturnState == IndirectReturnState.Needed && IsLastBlockInMethod(block)) { HandleReturn(); } if (hasLocals) { foreach (var local in block.Locals) { FreeLocal(local); } _builder.CloseLocalScope(); } } private void EmitStatements(ImmutableArray<BoundStatement> statements) { foreach (var statement in statements) { EmitStatement(statement); } } private void EmitScope(BoundScope block) { Debug.Assert(!block.Locals.IsEmpty); _builder.OpenLocalScope(); foreach (var local in block.Locals) { Debug.Assert(local.Name != null); Debug.Assert(local.SynthesizedKind == SynthesizedLocalKind.UserDefined && (local.ScopeDesignatorOpt?.Kind() == SyntaxKind.SwitchSection || local.ScopeDesignatorOpt?.Kind() == SyntaxKind.SwitchExpressionArm)); if (!local.IsConst && !IsStackLocal(local)) { _builder.AddLocalToScope(_builder.LocalSlotManager.GetLocal(local)); } } EmitStatements(block.Statements); _builder.CloseLocalScope(); } private void EmitStateMachineScope(BoundStateMachineScope scope) { _builder.OpenLocalScope(ScopeType.StateMachineVariable); foreach (var field in scope.Fields) { _builder.DefineUserDefinedStateMachineHoistedLocal(field.SlotIndex); } EmitStatement(scope.Statement); _builder.CloseLocalScope(); } // There are two ways a value can be returned from a function: // - Using ret opcode // - Store return value if any to a predefined temp and jump to the epilogue block // Sometimes ret is not an option (try/catch etc.). We also do this when emitting // debuggable code. This function is a stub for the logic that decides that. private bool ShouldUseIndirectReturn() { // If the method/lambda body is a block we define a sequence point for the closing brace of the body // and associate it with the ret instruction. If there is a return statement we need to store the value // to a long-lived synthesized local since a sequence point requires an empty evaluation stack. // // The emitted pattern is: // <evaluate return statement expression> // stloc $ReturnValue // ldloc $ReturnValue // sequence point // ret // // Do not emit this pattern if the method doesn't include user code or doesn't have a block body. return _ilEmitStyle == ILEmitStyle.Debug && _method.GenerateDebugInfo && _methodBodySyntaxOpt?.IsKind(SyntaxKind.Block) == true || _builder.InExceptionHandler; } // Compiler generated return mapped to a block is very likely the synthetic return // that was added at the end of the last block of a void method by analysis. // This is likely to be the last return in the method, so if we have not yet // emitted return sequence, it is convenient to do it right here (if we can). private bool CanHandleReturnLabel(BoundReturnStatement boundReturnStatement) { return boundReturnStatement.WasCompilerGenerated && (boundReturnStatement.Syntax.IsKind(SyntaxKind.Block) || _method?.IsImplicitConstructor == true) && !_builder.InExceptionHandler; } private void EmitReturnStatement(BoundReturnStatement boundReturnStatement) { var expressionOpt = boundReturnStatement.ExpressionOpt; if (boundReturnStatement.RefKind == RefKind.None) { this.EmitExpression(expressionOpt, true); } else { // NOTE: passing "ReadOnlyStrict" here. // we should never return an address of a copy var unexpectedTemp = this.EmitAddress(expressionOpt, this._method.RefKind == RefKind.RefReadOnly ? AddressKind.ReadOnlyStrict : AddressKind.Writeable); Debug.Assert(unexpectedTemp == null, "ref-returning a temp?"); } if (ShouldUseIndirectReturn()) { if (expressionOpt != null) { _builder.EmitLocalStore(LazyReturnTemp); } if (_indirectReturnState != IndirectReturnState.Emitted && CanHandleReturnLabel(boundReturnStatement)) { HandleReturn(); } else { _builder.EmitBranch(ILOpCode.Br, s_returnLabel); if (_indirectReturnState == IndirectReturnState.NotNeeded) { _indirectReturnState = IndirectReturnState.Needed; } } } else { if (_indirectReturnState == IndirectReturnState.Needed && CanHandleReturnLabel(boundReturnStatement)) { if (expressionOpt != null) { _builder.EmitLocalStore(LazyReturnTemp); } HandleReturn(); } else { if (expressionOpt != null) { // Ensure the return type has been translated. (Necessary // for cases of untranslated anonymous types.) _module.Translate(expressionOpt.Type, boundReturnStatement.Syntax, _diagnostics); } _builder.EmitRet(expressionOpt == null); } } } private void EmitTryStatement(BoundTryStatement statement, bool emitCatchesOnly = false) { Debug.Assert(!statement.CatchBlocks.IsDefault); // Stack must be empty at beginning of try block. _builder.AssertStackEmpty(); // IL requires catches and finally block to be distinct try // blocks so if the source contained both a catch and // a finally, nested scopes are emitted. bool emitNestedScopes = (!emitCatchesOnly && (statement.CatchBlocks.Length > 0) && (statement.FinallyBlockOpt != null)); _builder.OpenLocalScope(ScopeType.TryCatchFinally); _builder.OpenLocalScope(ScopeType.Try); // IL requires catches and finally block to be distinct try // blocks so if the source contained both a catch and // a finally, nested scopes are emitted. _tryNestingLevel++; if (emitNestedScopes) { EmitTryStatement(statement, emitCatchesOnly: true); } else { EmitBlock(statement.TryBlock); } _tryNestingLevel--; // Close the Try scope _builder.CloseLocalScope(); if (!emitNestedScopes) { foreach (var catchBlock in statement.CatchBlocks) { EmitCatchBlock(catchBlock); } } if (!emitCatchesOnly && (statement.FinallyBlockOpt != null)) { _builder.OpenLocalScope(statement.PreferFaultHandler ? ScopeType.Fault : ScopeType.Finally); EmitBlock(statement.FinallyBlockOpt); // close Finally scope _builder.CloseLocalScope(); // close the whole try statement scope _builder.CloseLocalScope(); // in a case where we emit surrogate Finally using Fault, we emit code like this // // try{ // . . . // } fault { // finallyBlock; // } // finallyBlock; // // This is where the second copy of finallyBlock is emitted. if (statement.PreferFaultHandler) { var finallyClone = FinallyCloner.MakeFinallyClone(statement); EmitBlock(finallyClone); } } else { // close the whole try statement scope _builder.CloseLocalScope(); } } /// <remarks> /// The interesting part in the following method is the support for exception filters. /// === Example: /// /// try /// { /// TryBlock /// } /// catch (ExceptionType ex) when (Condition) /// { /// Handler /// } /// /// gets emitted as something like ===> /// /// Try /// TryBlock /// Filter /// var tmp = Pop() as {ExceptionType} /// if (tmp == null) /// { /// Push 0 /// } /// else /// { /// ex = tmp /// Push Condition ? 1 : 0 /// } /// End Filter // leaves 1 or 0 on the stack /// Catch // gets called after finalization of nested exception frames if condition above produced 1 /// Pop // CLR pushes the exception object again /// variable ex can be used here /// Handler /// EndCatch /// /// When evaluating `Condition` requires additional statements be executed first, those /// statements are stored in `catchBlock.ExceptionFilterPrologueOpt` and emitted before the condition. /// </remarks> private void EmitCatchBlock(BoundCatchBlock catchBlock) { object typeCheckFailedLabel = null; _builder.AdjustStack(1); // Account for exception on the stack. // Open appropriate exception handler scope. (Catch or Filter) // if it is a Filter, emit prologue that checks if the type on the stack // converts to what we want. if (catchBlock.ExceptionFilterOpt == null) { var exceptionType = ((object)catchBlock.ExceptionTypeOpt != null) ? _module.Translate(catchBlock.ExceptionTypeOpt, catchBlock.Syntax, _diagnostics) : _module.GetSpecialType(SpecialType.System_Object, catchBlock.Syntax, _diagnostics); _builder.OpenLocalScope(ScopeType.Catch, exceptionType); RecordAsyncCatchHandlerOffset(catchBlock); // Dev12 inserts the sequence point on catch clause without a filter, just before // the exception object is assigned to the variable. // // Also in Dev12 the exception variable scope span starts right after the stloc instruction and // ends right before leave instruction. So when stopped at the sequence point Dev12 inserts, // the exception variable is not visible. if (_emitPdbSequencePoints) { var syntax = catchBlock.Syntax as CatchClauseSyntax; if (syntax != null) { TextSpan spSpan; var declaration = syntax.Declaration; if (declaration == null) { spSpan = syntax.CatchKeyword.Span; } else { spSpan = TextSpan.FromBounds(syntax.SpanStart, syntax.Declaration.Span.End); } this.EmitSequencePoint(catchBlock.SyntaxTree, spSpan); } } } else { _builder.OpenLocalScope(ScopeType.Filter); RecordAsyncCatchHandlerOffset(catchBlock); // Filtering starts with simulating regular catch through a // type check. If this is not our type then we are done. var typeCheckPassedLabel = new object(); typeCheckFailedLabel = new object(); if ((object)catchBlock.ExceptionTypeOpt != null) { var exceptionType = _module.Translate(catchBlock.ExceptionTypeOpt, catchBlock.Syntax, _diagnostics); _builder.EmitOpCode(ILOpCode.Isinst); _builder.EmitToken(exceptionType, catchBlock.Syntax, _diagnostics); _builder.EmitOpCode(ILOpCode.Dup); _builder.EmitBranch(ILOpCode.Brtrue, typeCheckPassedLabel); _builder.EmitOpCode(ILOpCode.Pop); _builder.EmitIntConstant(0); _builder.EmitBranch(ILOpCode.Br, typeCheckFailedLabel); } else { // no formal exception type means we always pass the check } _builder.MarkLabel(typeCheckPassedLabel); } foreach (var local in catchBlock.Locals) { var declaringReferences = local.DeclaringSyntaxReferences; var localSyntax = !declaringReferences.IsEmpty ? (CSharpSyntaxNode)declaringReferences[0].GetSyntax() : catchBlock.Syntax; DefineLocal(local, localSyntax); } var exceptionSourceOpt = catchBlock.ExceptionSourceOpt; if (exceptionSourceOpt != null) { // here we have our exception on the stack in a form of a reference type (O) // it means that we have to "unbox" it before storing to the local // if exception's type is a generic type parameter. if (!exceptionSourceOpt.Type.IsVerifierReference()) { Debug.Assert(exceptionSourceOpt.Type.IsTypeParameter()); // only expecting type parameters _builder.EmitOpCode(ILOpCode.Unbox_any); EmitSymbolToken(exceptionSourceOpt.Type, exceptionSourceOpt.Syntax); } BoundExpression exceptionSource = exceptionSourceOpt; while (exceptionSource.Kind == BoundKind.Sequence) { var seq = (BoundSequence)exceptionSource; Debug.Assert(seq.Locals.IsDefaultOrEmpty); EmitSideEffects(seq); exceptionSource = seq.Value; } switch (exceptionSource.Kind) { case BoundKind.Local: var exceptionSourceLocal = (BoundLocal)exceptionSource; Debug.Assert(exceptionSourceLocal.LocalSymbol.RefKind == RefKind.None); if (!IsStackLocal(exceptionSourceLocal.LocalSymbol)) { _builder.EmitLocalStore(GetLocal(exceptionSourceLocal)); } break; case BoundKind.FieldAccess: var left = (BoundFieldAccess)exceptionSource; Debug.Assert(!left.FieldSymbol.IsStatic, "Not supported"); Debug.Assert(!left.ReceiverOpt.Type.IsTypeParameter()); var stateMachineField = left.FieldSymbol as StateMachineFieldSymbol; if (((object)stateMachineField != null) && (stateMachineField.SlotIndex >= 0)) { _builder.DefineUserDefinedStateMachineHoistedLocal(stateMachineField.SlotIndex); } // When assigning to a field // we need to push param address below the exception var temp = AllocateTemp(exceptionSource.Type, exceptionSource.Syntax); _builder.EmitLocalStore(temp); var receiverTemp = EmitReceiverRef(left.ReceiverOpt, AddressKind.Writeable); Debug.Assert(receiverTemp == null); _builder.EmitLocalLoad(temp); FreeTemp(temp); EmitFieldStore(left); break; default: throw ExceptionUtilities.UnexpectedValue(exceptionSource.Kind); } } else { _builder.EmitOpCode(ILOpCode.Pop); } if (catchBlock.ExceptionFilterPrologueOpt != null) { Debug.Assert(_builder.IsStackEmpty); EmitStatements(catchBlock.ExceptionFilterPrologueOpt.Statements); } // Emit the actual filter expression, if we have one, and normalize // results. if (catchBlock.ExceptionFilterOpt != null) { EmitCondExpr(catchBlock.ExceptionFilterOpt, true); // Normalize the return value because values other than 0 or 1 // produce unspecified results. _builder.EmitIntConstant(0); _builder.EmitOpCode(ILOpCode.Cgt_un); _builder.MarkLabel(typeCheckFailedLabel); // Now we are starting the actual handler _builder.MarkFilterConditionEnd(); // Pop the exception; it should have already been stored to the // variable by the filter. _builder.EmitOpCode(ILOpCode.Pop); } EmitBlock(catchBlock.Body); _builder.CloseLocalScope(); } private void RecordAsyncCatchHandlerOffset(BoundCatchBlock catchBlock) { if (catchBlock.IsSynthesizedAsyncCatchAll) { Debug.Assert(_asyncCatchHandlerOffset < 0); // only one expected _asyncCatchHandlerOffset = _builder.AllocateILMarker(); } } private void EmitSwitchDispatch(BoundSwitchDispatch dispatch) { // Switch expression must have a valid switch governing type Debug.Assert((object)dispatch.Expression.Type != null); Debug.Assert(dispatch.Expression.Type.IsValidV6SwitchGoverningType()); // We must have rewritten nullable switch expression into non-nullable constructs. Debug.Assert(!dispatch.Expression.Type.IsNullableType()); // This must be used only for nontrivial dispatches. Debug.Assert(dispatch.Cases.Any()); EmitSwitchHeader( dispatch.Expression, dispatch.Cases.Select(p => new KeyValuePair<ConstantValue, object>(p.value, p.label)).ToArray(), dispatch.DefaultLabel, dispatch.EqualityMethod); } private void EmitSwitchHeader( BoundExpression expression, KeyValuePair<ConstantValue, object>[] switchCaseLabels, LabelSymbol fallThroughLabel, MethodSymbol equalityMethod) { Debug.Assert(expression.ConstantValue == null); Debug.Assert((object)expression.Type != null && expression.Type.IsValidV6SwitchGoverningType()); Debug.Assert(switchCaseLabels.Length > 0); Debug.Assert(switchCaseLabels != null); LocalDefinition temp = null; LocalOrParameter key; BoundSequence sequence = null; if (expression.Kind == BoundKind.Sequence) { sequence = (BoundSequence)expression; DefineLocals(sequence); EmitSideEffects(sequence); expression = sequence.Value; } if (expression.Kind == BoundKind.SequencePointExpression) { var sequencePointExpression = (BoundSequencePointExpression)expression; EmitSequencePoint(sequencePointExpression); expression = sequencePointExpression.Expression; } switch (expression.Kind) { case BoundKind.Local: var local = ((BoundLocal)expression).LocalSymbol; if (local.RefKind == RefKind.None && !IsStackLocal(local)) { key = this.GetLocal(local); break; } goto default; case BoundKind.Parameter: var parameter = (BoundParameter)expression; if (parameter.ParameterSymbol.RefKind == RefKind.None) { key = ParameterSlot(parameter); break; } goto default; default: EmitExpression(expression, true); temp = AllocateTemp(expression.Type, expression.Syntax); _builder.EmitLocalStore(temp); key = temp; break; } // Emit switch jump table if (expression.Type.SpecialType != SpecialType.System_String) { _builder.EmitIntegerSwitchJumpTable(switchCaseLabels, fallThroughLabel, key, expression.Type.EnumUnderlyingTypeOrSelf().PrimitiveTypeCode); } else { this.EmitStringSwitchJumpTable(switchCaseLabels, fallThroughLabel, key, expression.Syntax, equalityMethod); } if (temp != null) { FreeTemp(temp); } if (sequence != null) { // sequence was used as a value, can release all its locals. FreeLocals(sequence); } } private void EmitStringSwitchJumpTable( KeyValuePair<ConstantValue, object>[] switchCaseLabels, LabelSymbol fallThroughLabel, LocalOrParameter key, SyntaxNode syntaxNode, MethodSymbol equalityMethod) { LocalDefinition keyHash = null; // Condition is necessary, but not sufficient (e.g. might be missing a special or well-known member). if (SwitchStringJumpTableEmitter.ShouldGenerateHashTableSwitch(_module, switchCaseLabels.Length)) { Debug.Assert(_module.SupportsPrivateImplClass); var privateImplClass = _module.GetPrivateImplClass(syntaxNode, _diagnostics); Cci.IReference stringHashMethodRef = privateImplClass.GetMethod(PrivateImplementationDetails.SynthesizedStringHashFunctionName); // Heuristics and well-known member availability determine the existence // of this helper. Rather than reproduce that (language-specific) logic here, // we simply check for the information we really want - whether the helper is // available. if (stringHashMethodRef != null) { // static uint ComputeStringHash(string s) // pop 1 (s) // push 1 (uint return value) // stackAdjustment = (pushCount - popCount) = 0 _builder.EmitLoad(key); _builder.EmitOpCode(ILOpCode.Call, stackAdjustment: 0); _builder.EmitToken(stringHashMethodRef, syntaxNode, _diagnostics); var UInt32Type = _module.Compilation.GetSpecialType(SpecialType.System_UInt32); keyHash = AllocateTemp(UInt32Type, syntaxNode); _builder.EmitLocalStore(keyHash); } } Cci.IReference stringEqualityMethodRef = _module.Translate(equalityMethod, syntaxNode, _diagnostics); Cci.IMethodReference stringLengthRef = null; var stringLengthMethod = _module.Compilation.GetSpecialTypeMember(SpecialMember.System_String__Length) as MethodSymbol; if (stringLengthMethod != null && !stringLengthMethod.HasUseSiteError) { stringLengthRef = _module.Translate(stringLengthMethod, syntaxNode, _diagnostics); } SwitchStringJumpTableEmitter.EmitStringCompareAndBranch emitStringCondBranchDelegate = (keyArg, stringConstant, targetLabel) => { if (stringConstant == ConstantValue.Null) { // if (key == null) // goto targetLabel _builder.EmitLoad(keyArg); _builder.EmitBranch(ILOpCode.Brfalse, targetLabel, ILOpCode.Brtrue); } else if (stringConstant.StringValue.Length == 0 && stringLengthRef != null) { // if (key != null && key.Length == 0) // goto targetLabel object skipToNext = new object(); _builder.EmitLoad(keyArg); _builder.EmitBranch(ILOpCode.Brfalse, skipToNext, ILOpCode.Brtrue); _builder.EmitLoad(keyArg); // Stack: key --> length _builder.EmitOpCode(ILOpCode.Call, 0); var diag = DiagnosticBag.GetInstance(); _builder.EmitToken(stringLengthRef, null, diag); Debug.Assert(diag.IsEmptyWithoutResolution); diag.Free(); _builder.EmitBranch(ILOpCode.Brfalse, targetLabel, ILOpCode.Brtrue); _builder.MarkLabel(skipToNext); } else { this.EmitStringCompareAndBranch(key, syntaxNode, stringConstant, targetLabel, stringEqualityMethodRef); } }; _builder.EmitStringSwitchJumpTable( caseLabels: switchCaseLabels, fallThroughLabel: fallThroughLabel, key: key, keyHash: keyHash, emitStringCondBranchDelegate: emitStringCondBranchDelegate, computeStringHashcodeDelegate: SynthesizedStringSwitchHashMethod.ComputeStringHash); if (keyHash != null) { FreeTemp(keyHash); } } /// <summary> /// Delegate to emit string compare call and conditional branch based on the compare result. /// </summary> /// <param name="key">Key to compare</param> /// <param name="syntaxNode">Node for diagnostics.</param> /// <param name="stringConstant">Case constant to compare the key against</param> /// <param name="targetLabel">Target label to branch to if key = stringConstant</param> /// <param name="stringEqualityMethodRef">String equality method</param> private void EmitStringCompareAndBranch(LocalOrParameter key, SyntaxNode syntaxNode, ConstantValue stringConstant, object targetLabel, Microsoft.Cci.IReference stringEqualityMethodRef) { // Emit compare and branch: // if (key == stringConstant) // goto targetLabel; Debug.Assert(stringEqualityMethodRef != null); #if DEBUG var assertDiagnostics = DiagnosticBag.GetInstance(); Debug.Assert(stringEqualityMethodRef == _module.Translate((MethodSymbol)_module.Compilation.GetSpecialTypeMember(SpecialMember.System_String__op_Equality), (CSharpSyntaxNode)syntaxNode, assertDiagnostics)); assertDiagnostics.Free(); #endif // static bool String.Equals(string a, string b) // pop 2 (a, b) // push 1 (bool return value) // stackAdjustment = (pushCount - popCount) = -1 _builder.EmitLoad(key); _builder.EmitConstantValue(stringConstant); _builder.EmitOpCode(ILOpCode.Call, stackAdjustment: -1); _builder.EmitToken(stringEqualityMethodRef, syntaxNode, _diagnostics); // Branch to targetLabel if String.Equals returned true. _builder.EmitBranch(ILOpCode.Brtrue, targetLabel, ILOpCode.Brfalse); } /// <summary> /// Gets already declared and initialized local. /// </summary> private LocalDefinition GetLocal(BoundLocal localExpression) { var symbol = localExpression.LocalSymbol; return GetLocal(symbol); } private LocalDefinition GetLocal(LocalSymbol symbol) { return _builder.LocalSlotManager.GetLocal(symbol); } private LocalDefinition DefineLocal(LocalSymbol local, SyntaxNode syntaxNode) { var dynamicTransformFlags = !local.IsCompilerGenerated && local.Type.ContainsDynamic() ? CSharpCompilation.DynamicTransformsEncoder.Encode(local.Type, RefKind.None, 0) : ImmutableArray<bool>.Empty; var tupleElementNames = !local.IsCompilerGenerated && local.Type.ContainsTupleNames() ? CSharpCompilation.TupleNamesEncoder.Encode(local.Type) : ImmutableArray<string>.Empty; if (local.IsConst) { Debug.Assert(local.HasConstantValue); MetadataConstant compileTimeValue = _module.CreateConstant(local.Type, local.ConstantValue, syntaxNode, _diagnostics); LocalConstantDefinition localConstantDef = new LocalConstantDefinition( local.Name, local.Locations.FirstOrDefault() ?? Location.None, compileTimeValue, dynamicTransformFlags: dynamicTransformFlags, tupleElementNames: tupleElementNames); _builder.AddLocalConstantToScope(localConstantDef); return null; } if (IsStackLocal(local)) { return null; } LocalSlotConstraints constraints; Cci.ITypeReference translatedType; if (local.DeclarationKind == LocalDeclarationKind.FixedVariable && local.IsPinned) // Excludes pointer local and string local in fixed string case. { Debug.Assert(local.RefKind == RefKind.None); Debug.Assert(local.TypeWithAnnotations.Type.IsPointerType()); constraints = LocalSlotConstraints.ByRef | LocalSlotConstraints.Pinned; PointerTypeSymbol pointerType = (PointerTypeSymbol)local.Type; TypeSymbol pointedAtType = pointerType.PointedAtType; // We can't declare a reference to void, so if the pointed-at type is void, use native int // (represented here by IntPtr) instead. translatedType = pointedAtType.IsVoidType() ? _module.GetSpecialType(SpecialType.System_IntPtr, syntaxNode, _diagnostics) : _module.Translate(pointedAtType, syntaxNode, _diagnostics); } else { constraints = (local.IsPinned ? LocalSlotConstraints.Pinned : LocalSlotConstraints.None) | (local.RefKind != RefKind.None ? LocalSlotConstraints.ByRef : LocalSlotConstraints.None); translatedType = _module.Translate(local.Type, syntaxNode, _diagnostics); } // Even though we don't need the token immediately, we will need it later when signature for the local is emitted. // Also, requesting the token has side-effect of registering types used, which is critical for embedded types (NoPia, VBCore, etc). _module.GetFakeSymbolTokenForIL(translatedType, syntaxNode, _diagnostics); LocalDebugId localId; var name = GetLocalDebugName(local, out localId); var localDef = _builder.LocalSlotManager.DeclareLocal( type: translatedType, symbol: local, name: name, kind: local.SynthesizedKind, id: localId, pdbAttributes: local.SynthesizedKind.PdbAttributes(), constraints: constraints, dynamicTransformFlags: dynamicTransformFlags, tupleElementNames: tupleElementNames, isSlotReusable: local.SynthesizedKind.IsSlotReusable(_ilEmitStyle != ILEmitStyle.Release)); // If named, add it to the local debug scope. if (localDef.Name != null && !(local.SynthesizedKind == SynthesizedLocalKind.UserDefined && // Visibility scope of such locals is represented by BoundScope node. (local.ScopeDesignatorOpt?.Kind() is SyntaxKind.SwitchSection or SyntaxKind.SwitchExpressionArm))) { _builder.AddLocalToScope(localDef); } return localDef; } /// <summary> /// Gets the name and id of the local that are going to be generated into the debug metadata. /// </summary> private string GetLocalDebugName(ILocalSymbolInternal local, out LocalDebugId localId) { localId = LocalDebugId.None; if (local.IsImportedFromMetadata) { return local.Name; } var localKind = local.SynthesizedKind; // only user-defined locals should be named during lowering: Debug.Assert((local.Name == null) == (localKind != SynthesizedLocalKind.UserDefined)); // Generating debug names for instrumentation payloads should be allowed, as described in https://github.com/dotnet/roslyn/issues/11024. // For now, skip naming locals generated by instrumentation as they might not have a local syntax offset. // Locals generated by instrumentation might exist in methods which do not contain a body (auto property initializers). if (!localKind.IsLongLived() || localKind == SynthesizedLocalKind.InstrumentationPayload) { return null; } if (_ilEmitStyle == ILEmitStyle.Debug) { var syntax = local.GetDeclaratorSyntax(); int syntaxOffset = _method.CalculateLocalSyntaxOffset(LambdaUtilities.GetDeclaratorPosition(syntax), syntax.SyntaxTree); int ordinal = _synthesizedLocalOrdinals.AssignLocalOrdinal(localKind, syntaxOffset); // user-defined locals should have 0 ordinal: Debug.Assert(ordinal == 0 || localKind != SynthesizedLocalKind.UserDefined); localId = new LocalDebugId(syntaxOffset, ordinal); } return local.Name ?? GeneratedNames.MakeSynthesizedLocalName(localKind, ref _uniqueNameId); } private bool IsSlotReusable(LocalSymbol local) { return local.SynthesizedKind.IsSlotReusable(_ilEmitStyle != ILEmitStyle.Release); } /// <summary> /// Releases a local. /// </summary> private void FreeLocal(LocalSymbol local) { // TODO: releasing named locals is NYI. if (local.Name == null && IsSlotReusable(local) && !IsStackLocal(local)) { _builder.LocalSlotManager.FreeLocal(local); } } /// <summary> /// Allocates a temp without identity. /// </summary> private LocalDefinition AllocateTemp(TypeSymbol type, SyntaxNode syntaxNode, LocalSlotConstraints slotConstraints = LocalSlotConstraints.None) { return _builder.LocalSlotManager.AllocateSlot( _module.Translate(type, syntaxNode, _diagnostics), slotConstraints); } /// <summary> /// Frees a temp. /// </summary> private void FreeTemp(LocalDefinition temp) { _builder.LocalSlotManager.FreeSlot(temp); } /// <summary> /// Frees an optional temp. /// </summary> private void FreeOptTemp(LocalDefinition temp) { if (temp != null) { FreeTemp(temp); } } /// <summary> /// Clones all labels used in a finally block. /// This allows creating an emittable clone of finally. /// It is safe to do because no branches can go in or out of the finally handler. /// </summary> private class FinallyCloner : BoundTreeRewriterWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator { private Dictionary<LabelSymbol, GeneratedLabelSymbol> _labelClones; private FinallyCloner() { } /// <summary> /// The argument is BoundTryStatement (and not a BoundBlock) specifically /// to support only Finally blocks where it is guaranteed to not have incoming or leaving branches. /// </summary> public static BoundBlock MakeFinallyClone(BoundTryStatement node) { var cloner = new FinallyCloner(); return (BoundBlock)cloner.Visit(node.FinallyBlockOpt); } public override BoundNode VisitLabelStatement(BoundLabelStatement node) { return node.Update(GetLabelClone(node.Label)); } public override BoundNode VisitGotoStatement(BoundGotoStatement node) { var labelClone = GetLabelClone(node.Label); // expressions do not contain labels or branches BoundExpression caseExpressionOpt = node.CaseExpressionOpt; // expressions do not contain labels or branches BoundLabel labelExpressionOpt = node.LabelExpressionOpt; return node.Update(labelClone, caseExpressionOpt, labelExpressionOpt); } public override BoundNode VisitConditionalGoto(BoundConditionalGoto node) { var labelClone = GetLabelClone(node.Label); // expressions do not contain labels or branches BoundExpression condition = node.Condition; return node.Update(condition, node.JumpIfTrue, labelClone); } public override BoundNode VisitSwitchDispatch(BoundSwitchDispatch node) { // expressions do not contain labels or branches BoundExpression expression = node.Expression; var defaultClone = GetLabelClone(node.DefaultLabel); var casesBuilder = ArrayBuilder<(ConstantValue, LabelSymbol)>.GetInstance(); foreach (var (value, label) in node.Cases) { casesBuilder.Add((value, GetLabelClone(label))); } return node.Update(expression, casesBuilder.ToImmutableAndFree(), defaultClone, node.EqualityMethod); } public override BoundNode VisitExpressionStatement(BoundExpressionStatement node) { // expressions do not contain labels or branches return node; } private GeneratedLabelSymbol GetLabelClone(LabelSymbol label) { var labelClones = _labelClones; if (labelClones == null) { _labelClones = labelClones = new Dictionary<LabelSymbol, GeneratedLabelSymbol>(); } GeneratedLabelSymbol clone; if (!labelClones.TryGetValue(label, out clone)) { clone = new GeneratedLabelSymbol("cloned_" + label.Name); labelClones.Add(label, clone); } return clone; } } } }
-1
dotnet/roslyn
55,419
Make vsix's compatible with vs 2022
Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
dibarbet
2021-08-04T23:36:41Z
2021-08-06T17:54:08Z
082df2aaf6a73277fc27f9d7a5a8d18ee45d7f8b
e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028
Make vsix's compatible with vs 2022. Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
./src/Compilers/Test/Resources/Core/MetadataTests/Invalid/Obfuscated2.dll
MZ@ !L!This program cannot be run in DOS mode. $PEL )R!  7 @ `\7O@`  H.text  `.rsrc@@@.reloc `@B7H# 6P 0%(0 }}*0{*0{*( * *0 +*0?~(  -!rp( o s ~ +*0 ~ +*"*Vs ( t*( *0 ~ +*0 (  +*( *( *0~o' +*0~o( +*0~o) +*0~ o* +*s+ s, s- s. *0 ( ( +*0 ( +*0  ( +*0 (! +*0  -(+ + +*"*( *01 {# o$  -(+ {# o%  +*J( s& }# *BSJB v4.0.30319lx#~L#Strings0L#US|#GUID#BlobW %3& 0= ,* P nnnnnn;O]nz  @"I zS " K:p[n) A \   TEip559 5 =A55 5   1-151=1F!o J V!R!J#!(!R<!!!!$!J!(!(!J!J"N$"S@"X\"^w"$"zM"R"c"V#h7#p@#JH##J JJJ !J )J 1J 9J AJ IJQJ YJ aJ JJJJJi| 'J,J39qJiJyJJJJ@ kHizMiRiV]oJ,4<D,J4J<JDJ)JJ.Sy.c.K.[. . 1.:.Y.#.+.3Y.;.CCKC{ixks{xsx{kss#k##sCCccK @` @``:>FKPUZ`einrxx |K    ZhxpK  35EcE<Module>System.Runtime.CompilerServicesCompilationRelaxationsAttribute.ctorRuntimeCompatibilityAttributeSystem.ReflectionAssemblyTitleAttributeAssemblyDescriptionAttributeAssemblyCompanyAttributeAssemblyProductAttributeAssemblyCopyrightAttributeAssemblyTrademarkAttributeSystem.Runtime.InteropServicesComVisibleAttributeGuidAttributeAssemblyFileVersionAttributeSystem.Runtime.VersioningTargetFrameworkAttributeSystemObjectSystem.ConfigurationApplicationSettingsBaseMicrosoft.VisualBasic.ApplicationServicesApplicationBaseMicrosoft.VisualBasic.DevicesComputerAttributeMicrosoft.VisualBasic.CompilerServicesStandardModuleAttributeSystem.CodeDom.CompilerGeneratedCodeAttributeSystem.DiagnosticsDebuggerNonUserCodeAttributeCompilerGeneratedAttributeMicrosoft.VisualBasicHideModuleNameAttributeSystem.ResourcesResourceManagerSystem.GlobalizationCultureInfoReferenceEqualsTypeRuntimeTypeHandleGetTypeFromHandleAssemblyget_AssemblySystem.ComponentModelEditorBrowsableAttributeEditorBrowsableStateSettingsBaseSynchronizedDebuggerHiddenAttributeMyGroupCollectionAttributeRuntimeHelpersGetObjectValueEqualsGetHashCodeToStringActivatorCreateInstanceMicrosoft.VisualBasic.MyServices.InternalContextValue`1aget_Valueset_ValueUserAttributeUsageAttributeAttributeTargetsTestObfuscatedClassLibrary.dllmscorlibDotfuscatorAttributeClass1TestObfuscatedClassLibraryResourcesTestObfuscatedClassLibrary.My.ResourcesMySettingsTestObfuscatedClassLibrary.MybcdMethod1abcdefA_0.cctoroACCultureDefaultTestObfuscatedClassLibrary.Resources.resourcesITestObfuscatedClassLibrary.ResourcesP0yr~G€ƈJ     ei m m uyy     ,   , ,,,( z\V4?_ :@3System.Resources.Tools.StronglyTypedResourceBuilder4.0.0.0YKMicrosoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator11.0.0.0 MyTemplate11.0.0.0a4System.Web.Services.Protocols.SoapHttpClientProtocolCreate__Instance__Dispose__Instance__ ]a]aa, ,,,( ( e0((]a$$RSA1m,|W;!ߦhz Z-iT~ZS-g͢)2+/es3Ijn24N8ֿ@FXJR\&"ڸ 0~{XTTWrapNonExceptionThrowsTestObfuscatedClassLibrary)$45f53b47-a830-4398-bf0e-11973e6b3ed8 1.0.0.0I.NETFramework,Version=v4.5TFrameworkDisplayName.NET Framework 4.57Mhijulwnyuowqxzxxv{}NOPQRS000:0:0:5.5.4521.29298]]a (elSystem.Resources.ResourceReader, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089#System.Resources.RuntimeResourceSetPADPADP77 7_CorDllMainmscoree.dll% 0HX@4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfo000004b0Comments"CompanyName^FileDescriptionTestObfuscatedClassLibrary0FileVersion1.0.0.0^InternalNameTestObfuscatedClassLibrary.dll&LegalCopyright*LegalTrademarksfOriginalFilenameTestObfuscatedClassLibrary.dllVProductNameTestObfuscatedClassLibrary4ProductVersion1.0.0.08Assembly Version1.0.0.00 7
MZ@ !L!This program cannot be run in DOS mode. $PEL )R!  7 @ `\7O@`  H.text  `.rsrc@@@.reloc `@B7H# 6P 0%(0 }}*0{*0{*( * *0 +*0?~(  -!rp( o s ~ +*0 ~ +*"*Vs ( t*( *0 ~ +*0 (  +*( *( *0~o' +*0~o( +*0~o) +*0~ o* +*s+ s, s- s. *0 ( ( +*0 ( +*0  ( +*0 (! +*0  -(+ + +*"*( *01 {# o$  -(+ {# o%  +*J( s& }# *BSJB v4.0.30319lx#~L#Strings0L#US|#GUID#BlobW %3& 0= ,* P nnnnnn;O]nz  @"I zS " K:p[n) A \   TEip559 5 =A55 5   1-151=1F!o J V!R!J#!(!R<!!!!$!J!(!(!J!J"N$"S@"X\"^w"$"zM"R"c"V#h7#p@#JH##J JJJ !J )J 1J 9J AJ IJQJ YJ aJ JJJJJi| 'J,J39qJiJyJJJJ@ kHizMiRiV]oJ,4<D,J4J<JDJ)JJ.Sy.c.K.[. . 1.:.Y.#.+.3Y.;.CCKC{ixks{xsx{kss#k##sCCccK @` @``:>FKPUZ`einrxx |K    ZhxpK  35EcE<Module>System.Runtime.CompilerServicesCompilationRelaxationsAttribute.ctorRuntimeCompatibilityAttributeSystem.ReflectionAssemblyTitleAttributeAssemblyDescriptionAttributeAssemblyCompanyAttributeAssemblyProductAttributeAssemblyCopyrightAttributeAssemblyTrademarkAttributeSystem.Runtime.InteropServicesComVisibleAttributeGuidAttributeAssemblyFileVersionAttributeSystem.Runtime.VersioningTargetFrameworkAttributeSystemObjectSystem.ConfigurationApplicationSettingsBaseMicrosoft.VisualBasic.ApplicationServicesApplicationBaseMicrosoft.VisualBasic.DevicesComputerAttributeMicrosoft.VisualBasic.CompilerServicesStandardModuleAttributeSystem.CodeDom.CompilerGeneratedCodeAttributeSystem.DiagnosticsDebuggerNonUserCodeAttributeCompilerGeneratedAttributeMicrosoft.VisualBasicHideModuleNameAttributeSystem.ResourcesResourceManagerSystem.GlobalizationCultureInfoReferenceEqualsTypeRuntimeTypeHandleGetTypeFromHandleAssemblyget_AssemblySystem.ComponentModelEditorBrowsableAttributeEditorBrowsableStateSettingsBaseSynchronizedDebuggerHiddenAttributeMyGroupCollectionAttributeRuntimeHelpersGetObjectValueEqualsGetHashCodeToStringActivatorCreateInstanceMicrosoft.VisualBasic.MyServices.InternalContextValue`1aget_Valueset_ValueUserAttributeUsageAttributeAttributeTargetsTestObfuscatedClassLibrary.dllmscorlibDotfuscatorAttributeClass1TestObfuscatedClassLibraryResourcesTestObfuscatedClassLibrary.My.ResourcesMySettingsTestObfuscatedClassLibrary.MybcdMethod1abcdefA_0.cctoroACCultureDefaultTestObfuscatedClassLibrary.Resources.resourcesITestObfuscatedClassLibrary.ResourcesP0yr~G€ƈJ     ei m m uyy     ,   , ,,,( z\V4?_ :@3System.Resources.Tools.StronglyTypedResourceBuilder4.0.0.0YKMicrosoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator11.0.0.0 MyTemplate11.0.0.0a4System.Web.Services.Protocols.SoapHttpClientProtocolCreate__Instance__Dispose__Instance__ ]a]aa, ,,,( ( e0((]a$$RSA1m,|W;!ߦhz Z-iT~ZS-g͢)2+/es3Ijn24N8ֿ@FXJR\&"ڸ 0~{XTTWrapNonExceptionThrowsTestObfuscatedClassLibrary)$45f53b47-a830-4398-bf0e-11973e6b3ed8 1.0.0.0I.NETFramework,Version=v4.5TFrameworkDisplayName.NET Framework 4.57Mhijulwnyuowqxzxxv{}NOPQRS000:0:0:5.5.4521.29298]]a (elSystem.Resources.ResourceReader, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089#System.Resources.RuntimeResourceSetPADPADP77 7_CorDllMainmscoree.dll% 0HX@4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfo000004b0Comments"CompanyName^FileDescriptionTestObfuscatedClassLibrary0FileVersion1.0.0.0^InternalNameTestObfuscatedClassLibrary.dll&LegalCopyright*LegalTrademarksfOriginalFilenameTestObfuscatedClassLibrary.dllVProductNameTestObfuscatedClassLibrary4ProductVersion1.0.0.08Assembly Version1.0.0.00 7
-1
dotnet/roslyn
55,419
Make vsix's compatible with vs 2022
Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
dibarbet
2021-08-04T23:36:41Z
2021-08-06T17:54:08Z
082df2aaf6a73277fc27f9d7a5a8d18ee45d7f8b
e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028
Make vsix's compatible with vs 2022. Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
./eng/common/sdl/init-sdl.ps1
Param( [string] $GuardianCliLocation, [string] $Repository, [string] $BranchName='master', [string] $WorkingDirectory, [string] $AzureDevOpsAccessToken, [string] $GuardianLoggerLevel='Standard' ) $ErrorActionPreference = 'Stop' Set-StrictMode -Version 2.0 $disableConfigureToolsetImport = $true $global:LASTEXITCODE = 0 # `tools.ps1` checks $ci to perform some actions. Since the SDL # scripts don't necessarily execute in the same agent that run the # build.ps1/sh script this variable isn't automatically set. $ci = $true . $PSScriptRoot\..\tools.ps1 # Don't display the console progress UI - it's a huge perf hit $ProgressPreference = 'SilentlyContinue' # Construct basic auth from AzDO access token; construct URI to the repository's gdn folder stored in that repository; construct location of zip file $encodedPat = [Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$AzureDevOpsAccessToken")) $escapedRepository = [Uri]::EscapeDataString("/$Repository/$BranchName/.gdn") $uri = "https://dev.azure.com/dnceng/internal/_apis/git/repositories/sdl-tool-cfg/Items?path=$escapedRepository&versionDescriptor[versionOptions]=0&`$format=zip&api-version=5.0" $zipFile = "$WorkingDirectory/gdn.zip" Add-Type -AssemblyName System.IO.Compression.FileSystem $gdnFolder = (Join-Path $WorkingDirectory '.gdn') try { # if the folder does not exist, we'll do a guardian init and push it to the remote repository Write-Host 'Initializing Guardian...' Write-Host "$GuardianCliLocation init --working-directory $WorkingDirectory --logger-level $GuardianLoggerLevel" & $GuardianCliLocation init --working-directory $WorkingDirectory --logger-level $GuardianLoggerLevel if ($LASTEXITCODE -ne 0) { Write-PipelineTelemetryError -Force -Category 'Build' -Message "Guardian init failed with exit code $LASTEXITCODE." ExitWithExitCode $LASTEXITCODE } # We create the mainbaseline so it can be edited later Write-Host "$GuardianCliLocation baseline --working-directory $WorkingDirectory --name mainbaseline" & $GuardianCliLocation baseline --working-directory $WorkingDirectory --name mainbaseline if ($LASTEXITCODE -ne 0) { Write-PipelineTelemetryError -Force -Category 'Build' -Message "Guardian baseline failed with exit code $LASTEXITCODE." ExitWithExitCode $LASTEXITCODE } ExitWithExitCode 0 } catch { Write-Host $_.ScriptStackTrace Write-PipelineTelemetryError -Force -Category 'Sdl' -Message $_ ExitWithExitCode 1 }
Param( [string] $GuardianCliLocation, [string] $Repository, [string] $BranchName='master', [string] $WorkingDirectory, [string] $AzureDevOpsAccessToken, [string] $GuardianLoggerLevel='Standard' ) $ErrorActionPreference = 'Stop' Set-StrictMode -Version 2.0 $disableConfigureToolsetImport = $true $global:LASTEXITCODE = 0 # `tools.ps1` checks $ci to perform some actions. Since the SDL # scripts don't necessarily execute in the same agent that run the # build.ps1/sh script this variable isn't automatically set. $ci = $true . $PSScriptRoot\..\tools.ps1 # Don't display the console progress UI - it's a huge perf hit $ProgressPreference = 'SilentlyContinue' # Construct basic auth from AzDO access token; construct URI to the repository's gdn folder stored in that repository; construct location of zip file $encodedPat = [Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$AzureDevOpsAccessToken")) $escapedRepository = [Uri]::EscapeDataString("/$Repository/$BranchName/.gdn") $uri = "https://dev.azure.com/dnceng/internal/_apis/git/repositories/sdl-tool-cfg/Items?path=$escapedRepository&versionDescriptor[versionOptions]=0&`$format=zip&api-version=5.0" $zipFile = "$WorkingDirectory/gdn.zip" Add-Type -AssemblyName System.IO.Compression.FileSystem $gdnFolder = (Join-Path $WorkingDirectory '.gdn') try { # if the folder does not exist, we'll do a guardian init and push it to the remote repository Write-Host 'Initializing Guardian...' Write-Host "$GuardianCliLocation init --working-directory $WorkingDirectory --logger-level $GuardianLoggerLevel" & $GuardianCliLocation init --working-directory $WorkingDirectory --logger-level $GuardianLoggerLevel if ($LASTEXITCODE -ne 0) { Write-PipelineTelemetryError -Force -Category 'Build' -Message "Guardian init failed with exit code $LASTEXITCODE." ExitWithExitCode $LASTEXITCODE } # We create the mainbaseline so it can be edited later Write-Host "$GuardianCliLocation baseline --working-directory $WorkingDirectory --name mainbaseline" & $GuardianCliLocation baseline --working-directory $WorkingDirectory --name mainbaseline if ($LASTEXITCODE -ne 0) { Write-PipelineTelemetryError -Force -Category 'Build' -Message "Guardian baseline failed with exit code $LASTEXITCODE." ExitWithExitCode $LASTEXITCODE } ExitWithExitCode 0 } catch { Write-Host $_.ScriptStackTrace Write-PipelineTelemetryError -Force -Category 'Sdl' -Message $_ ExitWithExitCode 1 }
-1
dotnet/roslyn
55,419
Make vsix's compatible with vs 2022
Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
dibarbet
2021-08-04T23:36:41Z
2021-08-06T17:54:08Z
082df2aaf6a73277fc27f9d7a5a8d18ee45d7f8b
e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028
Make vsix's compatible with vs 2022. Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
./src/EditorFeatures/VisualBasicTest/AddObsoleteAttribute/AddObsoleteAttributeTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic.AddObsoleteAttribute Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.AddObsoleteAttribute Public Class AddObsoleteAttributeTests Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider) Return (Nothing, New VisualBasicAddObsoleteAttributeCodeFixProvider()) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddObsoleteAttribute)> Public Async Function TestObsoleteClassNoMessage() As Task Await TestInRegularAndScript1Async( " <System.Obsolete> class Base end class class Derived inherits [||]Base end class ", " <System.Obsolete> class Base end class <System.Obsolete> class Derived inherits Base end class ") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddObsoleteAttribute)> Public Async Function TestObsoleteClassWithMessage() As Task Await TestInRegularAndScript1Async( " <System.Obsolete(""message"")> class Base end class class Derived inherits [||]Base end class ", " <System.Obsolete(""message"")> class Base end class <System.Obsolete> class Derived inherits Base end class ") End function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddObsoleteAttribute)> Public Async Function TestObsoleteClassUsedInField() As Task Await TestInRegularAndScript1Async( " <System.Obsolete> class Base public shared i as integer end class class Derived dim i = [||]Base.i end class ", " <System.Obsolete> class Base public shared i as integer end class class Derived <System.Obsolete> dim i = Base.i end class ") End function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddObsoleteAttribute)> Public Async Function TestObsoleteClassUsedInMethod() As Task Await TestInRegularAndScript1Async( " <System.Obsolete> class Base public shared i as integer end class class Derived sub Goo() dim i = [||]Base.i end sub end class ", " <System.Obsolete> class Base public shared i as integer end class class Derived <System.Obsolete> sub Goo() dim i = Base.i end sub end class ") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddObsoleteAttribute)> Public Async Function TestObsoleteOverride() As Task ' VB gives no error here. Await TestMissingAsync( " class Base <System.Obsolete> protected overridable sub ObMethod() end sub end class class Derived inherits Base protected overrides sub [||]ObMethod() end sub end class ") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddObsoleteAttribute)> Public Async Function TestObsoleteClassFixAll1() As Task Await TestInRegularAndScript1Async( " <System.Obsolete> class Base public shared i as integer end class class Derived sub Goo() dim i = {|FixAllInDocument:|}Base.i dim j = Base.i end sub end class ", " <System.Obsolete> class Base public shared i as integer end class class Derived <System.Obsolete> sub Goo() dim i = Base.i dim j = Base.i end sub end class ") End function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddObsoleteAttribute)> Public Async Function TestObsoleteClassFixAll2() As Task Await TestInRegularAndScript1Async( " <System.Obsolete> class Base public shared i as integer end class class Derived sub Goo() dim i = Base.i dim j = {|FixAllInDocument:|}Base.i end sub end class ", " <System.Obsolete> class Base public shared i as integer end class class Derived <System.Obsolete> sub Goo() dim i = Base.i dim j = Base.i end sub end class ") End function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddObsoleteAttribute)> Public Async Function TestObsoleteClassFixAll3() As Task Await TestInRegularAndScript1Async( " <System.Obsolete> class Base public shared i as integer end class class Derived sub Goo() dim i = {|FixAllInDocument:|}Base.i end sub sub Bar() dim j = Base.i end sub end class ", " <System.Obsolete> class Base public shared i as integer end class class Derived <System.Obsolete> sub Goo() dim i = Base.i end sub <System.Obsolete> sub Bar() dim j = Base.i end sub end class ") End function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic.AddObsoleteAttribute Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.AddObsoleteAttribute Public Class AddObsoleteAttributeTests Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider) Return (Nothing, New VisualBasicAddObsoleteAttributeCodeFixProvider()) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddObsoleteAttribute)> Public Async Function TestObsoleteClassNoMessage() As Task Await TestInRegularAndScript1Async( " <System.Obsolete> class Base end class class Derived inherits [||]Base end class ", " <System.Obsolete> class Base end class <System.Obsolete> class Derived inherits Base end class ") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddObsoleteAttribute)> Public Async Function TestObsoleteClassWithMessage() As Task Await TestInRegularAndScript1Async( " <System.Obsolete(""message"")> class Base end class class Derived inherits [||]Base end class ", " <System.Obsolete(""message"")> class Base end class <System.Obsolete> class Derived inherits Base end class ") End function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddObsoleteAttribute)> Public Async Function TestObsoleteClassUsedInField() As Task Await TestInRegularAndScript1Async( " <System.Obsolete> class Base public shared i as integer end class class Derived dim i = [||]Base.i end class ", " <System.Obsolete> class Base public shared i as integer end class class Derived <System.Obsolete> dim i = Base.i end class ") End function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddObsoleteAttribute)> Public Async Function TestObsoleteClassUsedInMethod() As Task Await TestInRegularAndScript1Async( " <System.Obsolete> class Base public shared i as integer end class class Derived sub Goo() dim i = [||]Base.i end sub end class ", " <System.Obsolete> class Base public shared i as integer end class class Derived <System.Obsolete> sub Goo() dim i = Base.i end sub end class ") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddObsoleteAttribute)> Public Async Function TestObsoleteOverride() As Task ' VB gives no error here. Await TestMissingAsync( " class Base <System.Obsolete> protected overridable sub ObMethod() end sub end class class Derived inherits Base protected overrides sub [||]ObMethod() end sub end class ") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddObsoleteAttribute)> Public Async Function TestObsoleteClassFixAll1() As Task Await TestInRegularAndScript1Async( " <System.Obsolete> class Base public shared i as integer end class class Derived sub Goo() dim i = {|FixAllInDocument:|}Base.i dim j = Base.i end sub end class ", " <System.Obsolete> class Base public shared i as integer end class class Derived <System.Obsolete> sub Goo() dim i = Base.i dim j = Base.i end sub end class ") End function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddObsoleteAttribute)> Public Async Function TestObsoleteClassFixAll2() As Task Await TestInRegularAndScript1Async( " <System.Obsolete> class Base public shared i as integer end class class Derived sub Goo() dim i = Base.i dim j = {|FixAllInDocument:|}Base.i end sub end class ", " <System.Obsolete> class Base public shared i as integer end class class Derived <System.Obsolete> sub Goo() dim i = Base.i dim j = Base.i end sub end class ") End function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddObsoleteAttribute)> Public Async Function TestObsoleteClassFixAll3() As Task Await TestInRegularAndScript1Async( " <System.Obsolete> class Base public shared i as integer end class class Derived sub Goo() dim i = {|FixAllInDocument:|}Base.i end sub sub Bar() dim j = Base.i end sub end class ", " <System.Obsolete> class Base public shared i as integer end class class Derived <System.Obsolete> sub Goo() dim i = Base.i end sub <System.Obsolete> sub Bar() dim j = Base.i end sub end class ") End function End Class End Namespace
-1
dotnet/roslyn
55,419
Make vsix's compatible with vs 2022
Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
dibarbet
2021-08-04T23:36:41Z
2021-08-06T17:54:08Z
082df2aaf6a73277fc27f9d7a5a8d18ee45d7f8b
e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028
Make vsix's compatible with vs 2022. Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
./src/VisualStudio/VisualStudioDiagnosticsToolWindow/xlf/VisualStudioDiagnosticsWindow.vsct.zh-Hant.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="zh-Hant" original="../VisualStudioDiagnosticsWindow.vsct"> <body> <trans-unit id="cmdIDRoslynDiagnosticWindow|CommandName"> <source>cmdIDRoslynDiagnosticWindow</source> <target state="translated">cmdIDRoslynDiagnosticWindow</target> <note /> </trans-unit> <trans-unit id="cmdIDRoslynDiagnosticWindow|ButtonText"> <source>Roslyn Diagnostics</source> <target state="translated">Roslyn 診斷</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="zh-Hant" original="../VisualStudioDiagnosticsWindow.vsct"> <body> <trans-unit id="cmdIDRoslynDiagnosticWindow|CommandName"> <source>cmdIDRoslynDiagnosticWindow</source> <target state="translated">cmdIDRoslynDiagnosticWindow</target> <note /> </trans-unit> <trans-unit id="cmdIDRoslynDiagnosticWindow|ButtonText"> <source>Roslyn Diagnostics</source> <target state="translated">Roslyn 診斷</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,419
Make vsix's compatible with vs 2022
Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
dibarbet
2021-08-04T23:36:41Z
2021-08-06T17:54:08Z
082df2aaf6a73277fc27f9d7a5a8d18ee45d7f8b
e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028
Make vsix's compatible with vs 2022. Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
./src/EditorFeatures/CSharpTest/ConvertForEachToFor/ConvertForEachToForTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.ConvertForEachToFor; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertForEachToFor { public partial class ConvertForEachToForTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider( Workspace workspace, TestParameters parameters) => new CSharpConvertForEachToForCodeRefactoringProvider(); private readonly CodeStyleOption2<bool> onWithSilent = new CodeStyleOption2<bool>(true, NotificationOption2.Silent); private OptionsCollection ImplicitTypeEverywhere => new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, onWithSilent }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithSilent }, { CSharpCodeStyleOptions.VarForBuiltInTypes, onWithSilent }, }; [WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task EmptyBlockBody() { var text = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; foreach[||](var a in array) { } } } "; var expected = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; for (int {|Rename:i|} = 0; i < array.Length; i++) { int a = array[i]; } } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task EmptyBody() { var text = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; foreach[||](var a in array) ; } } "; var expected = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; for (int {|Rename:i|} = 0; i < array.Length; i++) ; } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task Body() { var text = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; foreach[||](var a in array) Console.WriteLine(a); } } "; var expected = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; for (int {|Rename:i|} = 0; i < array.Length; i++) { int a = array[i]; Console.WriteLine(a); } } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task BlockBody() { var text = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; foreach[||](var a in array) { Console.WriteLine(a); } } } "; var expected = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; for (int {|Rename:i|} = 0; i < array.Length; i++) { int a = array[i]; Console.WriteLine(a); } } } "; await TestInRegularAndScriptAsync(text, expected); } [WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task Comment() { var text = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; /* comment */ foreach[||](var a in array) /* comment */ { } } } "; var expected = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; /* comment */ for (int {|Rename:i|} = 0; i < array.Length; i++) /* comment */ { int a = array[i]; } } } "; await TestInRegularAndScriptAsync(text, expected); } [WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task Comment2() { var text = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; foreach[||](var a in array) /* comment */ { }/* comment */ } } "; var expected = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; for (int {|Rename:i|} = 0; i < array.Length; i++) /* comment */ { int a = array[i]; }/* comment */ } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task Comment3() { var text = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; foreach[||](var a in array) /* comment */; } } "; var expected = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; for (int {|Rename:i|} = 0; i < array.Length; i++) /* comment */; } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task Comment4() { var text = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; foreach[||](var a in array) Console.WriteLine(a); // test } } "; var expected = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; for (int {|Rename:i|} = 0; i < array.Length; i++) { int a = array[i]; Console.WriteLine(a); // test } } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task Comment5() { var text = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; foreach [||] (var a in array) /* test */ Console.WriteLine(a); } } "; var expected = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; for (int {|Rename:i|} = 0; i < array.Length; i++) /* test */ { int a = array[i]; Console.WriteLine(a); } } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task Comment6() { var text = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; foreach [||] (var a in array) /* test */ Console.WriteLine(a); } } "; var expected = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; for (int {|Rename:i|} = 0; i < array.Length; i++) { int a = array[i]; /* test */ Console.WriteLine(a); } } } "; await TestInRegularAndScriptAsync(text, expected); } [WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task Comment7() { var text = @" class Test { void Method() { // test foreach[||](var a in new int[] { 1, 3, 4 }) { } } } "; var expected = @" class Test { void Method() { // test int[] {|Rename:array|} = new int[] { 1, 3, 4 }; for (int {|Rename:i|} = 0; i < array.Length; i++) { int a = array[i]; } } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task TestCommentsInTheMiddleOfParentheses() { var text = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; foreach [||] (var a /* test */ in array) ; } } "; var expected = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; for (int {|Rename:i|} = 0; i < array.Length; i++) ; } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task TestCommentsAtBeginningOfParentheses() { var text = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; foreach [||] (/* test */ var a in array) ; } } "; var expected = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; for (int {|Rename:i|} = 0; i < array.Length; i++) ; } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task TestCommentsAtTheEndOfParentheses() { var text = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; foreach [||] (var a in array /* test */) ; } } "; var expected = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; for (int {|Rename:i|} = 0; i < array.Length; i++) ; } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task CollectionStatement() { var text = @" class Test { void Method() { foreach[||](var a in new int[] { 1, 3, 4 }) { Console.WriteLine(a); } } } "; var expected = @" class Test { void Method() { int[] {|Rename:array|} = new int[] { 1, 3, 4 }; for (int {|Rename:i|} = 0; i < array.Length; i++) { int a = array[i]; Console.WriteLine(a); } } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task CollectionConflict() { var text = @" class Test { void Method() { var array = 1; foreach[||](var a in new int[] { 1, 3, 4 }) { Console.WriteLine(a); } } } "; var expected = @" class Test { void Method() { var array = 1; int[] {|Rename:array1|} = new int[] { 1, 3, 4 }; for (int {|Rename:i|} = 0; i < array1.Length; i++) { int a = array1[i]; Console.WriteLine(a); } } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task VariableWritten() { var text = @" class Test { void Method() { var array = new[] { 1 }; foreach [||] (var a in array) { a = 1; } } } "; var expected = @" class Test { void Method() { var array = new[] { 1 }; for (int {|Rename:i|} = 0; i < array.Length; i++) { {|Warning:int a = array[i];|} a = 1; } } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task IndexConflict() { var text = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; foreach [||] (var a in array) { int i = 0; } } } "; var expected = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; for (int {|Rename:i1|} = 0; i1 < array.Length; i1++) { int a = array[i1]; int i = 0; } } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task StructPropertyReadFromAndDiscarded() { var text = @" class Test { struct Struct { public string Property { get; } } void Method() { var array = new[] { new Struct() }; foreach [||] (var a in array) { _ = a.Property; } } } "; var expected = @" class Test { struct Struct { public string Property { get; } } void Method() { var array = new[] { new Struct() }; for (int {|Rename:i|} = 0; i < array.Length; i++) { Struct a = array[i]; _ = a.Property; } } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task StructPropertyReadFromAndAssignedToLocal() { var text = @" class Test { struct Struct { public string Property { get; } } void Method() { var array = new[] { new Struct() }; foreach [||] (var a in array) { var b = a.Property; } } } "; var expected = @" class Test { struct Struct { public string Property { get; } } void Method() { var array = new[] { new Struct() }; for (int {|Rename:i|} = 0; i < array.Length; i++) { Struct a = array[i]; var b = a.Property; } } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task WrongCaretPosition() { var text = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; foreach (var a in array) { [||] } } } "; await TestMissingInRegularAndScriptAsync(text); } [WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task TestCaretBefore() { var text = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; [||] foreach(var a in array) { } } } "; var expected = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; for (int {|Rename:i|} = 0; i < array.Length; i++) { int a = array[i]; } } } "; await TestInRegularAndScriptAsync(text, expected); } [WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task TestCaretAfter() { var text = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; foreach(var a in array) [||] { } } } "; var expected = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; for (int {|Rename:i|} = 0; i < array.Length; i++) { int a = array[i]; } } } "; await TestInRegularAndScriptAsync(text, expected); } [WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task TestSelection() { var text = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; [|foreach(var a in array) { }|] } } "; var expected = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; for (int {|Rename:i|} = 0; i < array.Length; i++) { int a = array[i]; } } } "; await TestInRegularAndScriptAsync(text, expected); } [WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task Field() { var text = @" class Test { int[] array = new int[] { 1, 3, 4 }; void Method() { foreach [||] (var a in array) { } } } "; var expected = @" class Test { int[] array = new int[] { 1, 3, 4 }; void Method() { for (int {|Rename:i|} = 0; i < array.Length; i++) { int a = array[i]; } } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task ArrayElement() { var text = @" class Test { void Method() { var array = new int[][] { new int[] { 1, 3, 4 } }; foreach [||] (var a in array[0]) { Console.WriteLine(a); } } } "; var expected = @" class Test { void Method() { var array = new int[][] { new int[] { 1, 3, 4 } }; for (int {|Rename:i|} = 0; i < array[0].Length; i++) { int a = array[0][i]; Console.WriteLine(a); } } } "; await TestInRegularAndScriptAsync(text, expected); } [WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task Parameter() { var text = @" class Test { void Method(int[] array) { foreach [||] (var a in array) { } } } "; var expected = @" class Test { void Method(int[] array) { for (int {|Rename:i|} = 0; i < array.Length; i++) { int a = array[i]; } } } "; await TestInRegularAndScriptAsync(text, expected); } [WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task Property() { var text = @" class Test { int [] Prop { get; } = new int[] { 1, 2, 3 }; void Method() { foreach [||] (var a in Prop) { } } } "; var expected = @" class Test { int [] Prop { get; } = new int[] { 1, 2, 3 }; void Method() { for (int {|Rename:i|} = 0; i < Prop.Length; i++) { int a = Prop[i]; } } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task Interface() { var text = @" using System.Collections.Generic; class Test { void Method() { var array = (IList<int>)(new int[] { 1, 3, 4 }); foreach[||] (var a in array) { Console.WriteLine(a); } } } "; var expected = @" using System.Collections.Generic; class Test { void Method() { var array = (IList<int>)(new int[] { 1, 3, 4 }); for (int {|Rename:i|} = 0; i < array.Count; i++) { int a = array[i]; Console.WriteLine(a); } } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task IListOfT() { var text = @" using System.Collections.Generic; class Test { void Method() { var list = new List<int>(); foreach [||](var a in list) { Console.WriteLine(a); } } } "; var expected = @" using System.Collections.Generic; class Test { void Method() { var list = new List<int>(); for (int {|Rename:i|} = 0; i < list.Count; i++) { int a = list[i]; Console.WriteLine(a); } } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task IReadOnlyListOfT() { var text = @" using System.Collections; using System.Collections.Generic; class Test { void Method() { var list = new ReadOnly<int>(); foreach [||](var a in list) { Console.WriteLine(a); } } } class ReadOnly<T> : IReadOnlyList<T> { public T this[int index] => throw new System.NotImplementedException(); public int Count => throw new System.NotImplementedException(); public IEnumerator<T> GetEnumerator() => throw new System.NotImplementedException(); IEnumerator IEnumerable.GetEnumerator() => throw new System.NotImplementedException(); } "; var expected = @" using System.Collections; using System.Collections.Generic; class Test { void Method() { var list = new ReadOnly<int>(); for (int {|Rename:i|} = 0; i < list.Count; i++) { int a = list[i]; Console.WriteLine(a); } } } class ReadOnly<T> : IReadOnlyList<T> { public T this[int index] => throw new System.NotImplementedException(); public int Count => throw new System.NotImplementedException(); public IEnumerator<T> GetEnumerator() => throw new System.NotImplementedException(); IEnumerator IEnumerable.GetEnumerator() => throw new System.NotImplementedException(); } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task IList() { var text = @" using System; using System.Collections; class Test { void Method() { var list = new List(); foreach [||](var a in list) { Console.WriteLine(a); } } } class List : IList { public object this[int index] { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } public bool IsReadOnly => throw new NotImplementedException(); public bool IsFixedSize => throw new NotImplementedException(); public int Count => throw new NotImplementedException(); public object SyncRoot => throw new NotImplementedException(); public bool IsSynchronized => throw new NotImplementedException(); public int Add(object value) => throw new NotImplementedException(); public void Clear() => throw new NotImplementedException(); public bool Contains(object value) => throw new NotImplementedException(); public void CopyTo(Array array, int index) => throw new NotImplementedException(); public IEnumerator GetEnumerator() => throw new NotImplementedException(); public int IndexOf(object value) => throw new NotImplementedException(); public void Insert(int index, object value) => throw new NotImplementedException(); public void Remove(object value) => throw new NotImplementedException(); public void RemoveAt(int index) => throw new NotImplementedException(); } "; var expected = @" using System; using System.Collections; class Test { void Method() { var list = new List(); for (int {|Rename:i|} = 0; i < list.Count; i++) { object a = list[i]; Console.WriteLine(a); } } } class List : IList { public object this[int index] { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } public bool IsReadOnly => throw new NotImplementedException(); public bool IsFixedSize => throw new NotImplementedException(); public int Count => throw new NotImplementedException(); public object SyncRoot => throw new NotImplementedException(); public bool IsSynchronized => throw new NotImplementedException(); public int Add(object value) => throw new NotImplementedException(); public void Clear() => throw new NotImplementedException(); public bool Contains(object value) => throw new NotImplementedException(); public void CopyTo(Array array, int index) => throw new NotImplementedException(); public IEnumerator GetEnumerator() => throw new NotImplementedException(); public int IndexOf(object value) => throw new NotImplementedException(); public void Insert(int index, object value) => throw new NotImplementedException(); public void Remove(object value) => throw new NotImplementedException(); public void RemoveAt(int index) => throw new NotImplementedException(); } "; await TestInRegularAndScriptAsync(text, expected); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/29740"), Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task ImmutableArray() { var text = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <MetadataReference>" + typeof(ImmutableArray<>).Assembly.Location + @"</MetadataReference> <Document> using System; using System.Collections.Immutable; class Test { void Method() { var list = ImmutableArray.Create(1); foreach [||](var a in list) { Console.WriteLine(a); } } }</Document> </Project> </Workspace>"; var expected = @" using System; using System.Collections.Immutable; class Test { void Method() { var list = ImmutableArray.Create(1); for (int {|Rename:i|} = 0; i < list.Length; i++) { int a = list[i]; Console.WriteLine(a); } } }"; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task ExplicitInterface() { var text = @" using System; using System.Collections; using System.Collections.Generic; class Test { void Method() { var list = new Explicit(); foreach [||] (var a in list) { Console.WriteLine(a); } } } class Explicit : IReadOnlyList<int> { int IReadOnlyList<int>.this[int index] => throw new NotImplementedException(); int IReadOnlyCollection<int>.Count => throw new NotImplementedException(); IEnumerator<int> IEnumerable<int>.GetEnumerator() => throw new NotImplementedException(); IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException(); } "; var expected = @" using System; using System.Collections; using System.Collections.Generic; class Test { void Method() { var list = new Explicit(); IReadOnlyList<int> {|Rename:list1|} = list; for (int {|Rename:i|} = 0; i < list1.Count; i++) { int a = list1[i]; Console.WriteLine(a); } } } class Explicit : IReadOnlyList<int> { int IReadOnlyList<int>.this[int index] => throw new NotImplementedException(); int IReadOnlyCollection<int>.Count => throw new NotImplementedException(); IEnumerator<int> IEnumerable<int>.GetEnumerator() => throw new NotImplementedException(); IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException(); } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task DoubleExplicitInterface() { var text = @" using System; using System.Collections; using System.Collections.Generic; class Test { void Method() { var list = new Explicit(); foreach [||] (var a in list) { Console.WriteLine(a); } } } class Explicit : IReadOnlyList<int>, IReadOnlyList<string> { int IReadOnlyList<int>.this[int index] => throw new NotImplementedException(); int IReadOnlyCollection<int>.Count => throw new NotImplementedException(); IEnumerator<int> IEnumerable<int>.GetEnumerator() => throw new NotImplementedException(); IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException(); string IReadOnlyList<string>.this[int index] => throw new NotImplementedException(); int IReadOnlyCollection<string>.Count => throw new NotImplementedException(); IEnumerator<string> IEnumerable<string>.GetEnumerator() => throw new NotImplementedException(); } "; await TestMissingInRegularAndScriptAsync(text); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task DoubleExplicitInterfaceWithExplicitType() { var text = @" using System; using System.Collections; using System.Collections.Generic; class Test { void Method() { var list = new Explicit(); foreach [||] (int a in list) { Console.WriteLine(a); } } } class Explicit : IReadOnlyList<int>, IReadOnlyList<string> { int IReadOnlyList<int>.this[int index] => throw new NotImplementedException(); int IReadOnlyCollection<int>.Count => throw new NotImplementedException(); IEnumerator<int> IEnumerable<int>.GetEnumerator() => throw new NotImplementedException(); IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException(); string IReadOnlyList<string>.this[int index] => throw new NotImplementedException(); int IReadOnlyCollection<string>.Count => throw new NotImplementedException(); IEnumerator<string> IEnumerable<string>.GetEnumerator() => throw new NotImplementedException(); } "; var expected = @" using System; using System.Collections; using System.Collections.Generic; class Test { void Method() { var list = new Explicit(); IReadOnlyList<int> {|Rename:list1|} = list; for (int {|Rename:i|} = 0; i < list1.Count; i++) { int a = list1[i]; Console.WriteLine(a); } } } class Explicit : IReadOnlyList<int>, IReadOnlyList<string> { int IReadOnlyList<int>.this[int index] => throw new NotImplementedException(); int IReadOnlyCollection<int>.Count => throw new NotImplementedException(); IEnumerator<int> IEnumerable<int>.GetEnumerator() => throw new NotImplementedException(); IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException(); string IReadOnlyList<string>.this[int index] => throw new NotImplementedException(); int IReadOnlyCollection<string>.Count => throw new NotImplementedException(); IEnumerator<string> IEnumerable<string>.GetEnumerator() => throw new NotImplementedException(); } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task MixedInterfaceImplementation() { var text = @" using System; using System.Collections; using System.Collections.Generic; class Test { void Method() { var list = new Mixed(); foreach [||] (var a in list) { Console.WriteLine(a); } } } class Mixed : IReadOnlyList<int>, IReadOnlyList<string> { public int this[int index] => throw new NotImplementedException(); public int Count => throw new NotImplementedException(); public IEnumerator<int> GetEnumerator() => throw new NotImplementedException(); IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException(); string IReadOnlyList<string>.this[int index] => throw new NotImplementedException(); int IReadOnlyCollection<string>.Count => throw new NotImplementedException(); IEnumerator<string> IEnumerable<string>.GetEnumerator() => throw new NotImplementedException(); } "; var expected = @" using System; using System.Collections; using System.Collections.Generic; class Test { void Method() { var list = new Mixed(); for (int {|Rename:i|} = 0; i < list.Count; i++) { int a = list[i]; Console.WriteLine(a); } } } class Mixed : IReadOnlyList<int>, IReadOnlyList<string> { public int this[int index] => throw new NotImplementedException(); public int Count => throw new NotImplementedException(); public IEnumerator<int> GetEnumerator() => throw new NotImplementedException(); IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException(); string IReadOnlyList<string>.this[int index] => throw new NotImplementedException(); int IReadOnlyCollection<string>.Count => throw new NotImplementedException(); IEnumerator<string> IEnumerable<string>.GetEnumerator() => throw new NotImplementedException(); } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task MixedInterfaceImplementationWithExplicitType() { var text = @" using System; using System.Collections; using System.Collections.Generic; class Test { void Method() { var list = new Mixed(); foreach [||] (string a in list) { Console.WriteLine(a); } } } class Mixed : IReadOnlyList<int>, IReadOnlyList<string> { public int this[int index] => throw new NotImplementedException(); public int Count => throw new NotImplementedException(); public IEnumerator<int> GetEnumerator() => throw new NotImplementedException(); IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException(); string IReadOnlyList<string>.this[int index] => throw new NotImplementedException(); int IReadOnlyCollection<string>.Count => throw new NotImplementedException(); IEnumerator<string> IEnumerable<string>.GetEnumerator() => throw new NotImplementedException(); } "; var expected = @" using System; using System.Collections; using System.Collections.Generic; class Test { void Method() { var list = new Mixed(); IReadOnlyList<string> {|Rename:list1|} = list; for (int {|Rename:i|} = 0; i < list1.Count; i++) { string a = list1[i]; Console.WriteLine(a); } } } class Mixed : IReadOnlyList<int>, IReadOnlyList<string> { public int this[int index] => throw new NotImplementedException(); public int Count => throw new NotImplementedException(); public IEnumerator<int> GetEnumerator() => throw new NotImplementedException(); IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException(); string IReadOnlyList<string>.this[int index] => throw new NotImplementedException(); int IReadOnlyCollection<string>.Count => throw new NotImplementedException(); IEnumerator<string> IEnumerable<string>.GetEnumerator() => throw new NotImplementedException(); } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task PreserveUserExpression() { var text = @" using System; using System.Collections; using System.Collections.Generic; namespace NS { class Test { void Method() { foreach [||] (string a in new NS.Mixed()) { Console.WriteLine(a); } } } class Mixed : IReadOnlyList<int>, IReadOnlyList<string> { public int this[int index] => throw new NotImplementedException(); public int Count => throw new NotImplementedException(); public IEnumerator<int> GetEnumerator() => throw new NotImplementedException(); IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException(); string IReadOnlyList<string>.this[int index] => throw new NotImplementedException(); int IReadOnlyCollection<string>.Count => throw new NotImplementedException(); IEnumerator<string> IEnumerable<string>.GetEnumerator() => throw new NotImplementedException(); } } "; var expected = @" using System; using System.Collections; using System.Collections.Generic; namespace NS { class Test { void Method() { IReadOnlyList<string> {|Rename:list|} = new NS.Mixed(); for (int {|Rename:i|} = 0; i < list.Count; i++) { string a = list[i]; Console.WriteLine(a); } } } class Mixed : IReadOnlyList<int>, IReadOnlyList<string> { public int this[int index] => throw new NotImplementedException(); public int Count => throw new NotImplementedException(); public IEnumerator<int> GetEnumerator() => throw new NotImplementedException(); IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException(); string IReadOnlyList<string>.this[int index] => throw new NotImplementedException(); int IReadOnlyCollection<string>.Count => throw new NotImplementedException(); IEnumerator<string> IEnumerable<string>.GetEnumerator() => throw new NotImplementedException(); } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task EmbededStatement() { var text = @" class Test { void Method() { if (true) foreach [||] (var a in new int[] {}); } } "; await TestMissingInRegularAndScriptAsync(text); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task EmbededStatement2() { var text = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; if (true) foreach [||] (var a in array) Console.WriteLine(a); } } "; var expected = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; if (true) for (int {|Rename:i|} = 0; i < array.Length; i++) { int a = array[i]; Console.WriteLine(a); } } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task IndexConflict2() { var text = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; foreach [||] (var i in array) { Console.WriteLine(i); } } } "; var expected = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; for (int {|Rename:i1|} = 0; i1 < array.Length; i1++) { int i = array[i1]; Console.WriteLine(i); } } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task UseTypeAsUsedInForeach() { var text = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; foreach [||] (int a in array) { Console.WriteLine(i); } } } "; var expected = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; for (int {|Rename:i|} = 0; i < array.Length; i++) { int a = array[i]; Console.WriteLine(i); } } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task String() { var text = @" class Test { void Method() { foreach [||] (var a in ""test"") { Console.WriteLine(a); } } } "; var expected = @" class Test { void Method() { string {|Rename:str|} = ""test""; for (int {|Rename:i|} = 0; i < str.Length; i++) { char a = str[i]; Console.WriteLine(a); } } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task StringLocalConst() { var text = @" class Test { void Method() { const string test = ""test""; foreach [||] (var a in test) { Console.WriteLine(a); } } } "; var expected = @" class Test { void Method() { const string test = ""test""; for (int {|Rename:i|} = 0; i < test.Length; i++) { char a = test[i]; Console.WriteLine(a); } } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task StringConst() { var text = @" class Test { const string test = ""test""; void Method() { foreach [||] (var a in test) { Console.WriteLine(a); } } } "; var expected = @" class Test { const string test = ""test""; void Method() { for (int {|Rename:i|} = 0; i < test.Length; i++) { char a = test[i]; Console.WriteLine(a); } } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task ElementExplicitCast() { var text = @" class Test { void Method() { var array = new object[] { 1, 2, 3 }; foreach [||] (string a in array) { Console.WriteLine(a); } } } "; var expected = @" class Test { void Method() { var array = new object[] { 1, 2, 3 }; for (int {|Rename:i|} = 0; i < array.Length; i++) { string a = (string)array[i]; Console.WriteLine(a); } } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task NotAssignable() { var text = @" class Test { void Method() { var array = new int[] { 1, 2, 3 }; foreach [||] (string a in array) { Console.WriteLine(a); } } } "; await TestMissingInRegularAndScriptAsync(text); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task ElementMissing() { var text = @" class Test { void Method() { var array = new int[] { 1, 2, 3 }; foreach [||] (in array) { Console.WriteLine(a); } } } "; await TestMissingInRegularAndScriptAsync(text); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task ElementMissing2() { var text = @" class Test { void Method() { foreach [||] (string a in ) { Console.WriteLine(a); } } } "; await TestMissingInRegularAndScriptAsync(text); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task StringExplicitType() { var text = @" class Test { void Method() { foreach [||] (int a in ""test"") { Console.WriteLine(a); } } } "; var expected = @" class Test { void Method() { string {|Rename:str|} = ""test""; for (int {|Rename:i|} = 0; i < str.Length; i++) { int a = str[i]; Console.WriteLine(a); } } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task Var() { var text = @" using System; using System.Collections; using System.Collections.Generic; class Test { void Method() { var list = new Explicit(); foreach [||] (var a in list) { Console.WriteLine(a); } } } class Explicit : IReadOnlyList<int> { int IReadOnlyList<int>.this[int index] => throw new NotImplementedException(); int IReadOnlyCollection<int>.Count => throw new NotImplementedException(); IEnumerator<int> IEnumerable<int>.GetEnumerator() => throw new NotImplementedException(); IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException(); } "; var expected = @" using System; using System.Collections; using System.Collections.Generic; class Test { void Method() { var list = new Explicit(); var {|Rename:list1|} = (IReadOnlyList<int>)list; for (var {|Rename:i|} = 0; i < list1.Count; i++) { var a = list1[i]; Console.WriteLine(a); } } } class Explicit : IReadOnlyList<int> { int IReadOnlyList<int>.this[int index] => throw new NotImplementedException(); int IReadOnlyCollection<int>.Count => throw new NotImplementedException(); IEnumerator<int> IEnumerable<int>.GetEnumerator() => throw new NotImplementedException(); IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException(); } "; await TestInRegularAndScriptAsync(text, expected, options: ImplicitTypeEverywhere); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task ArrayRank2() { var text = @" class Test { void Method() { foreach [||] (int a in new int[,] { {1, 2} }) { Console.WriteLine(a); } } } "; await TestMissingAsync(text); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] [WorkItem(48950, "https://github.com/dotnet/roslyn/issues/48950")] public async Task NullableReferenceVar() { var text = @" #nullable enable class Test { void Method() { foreach [||] (var s in new string[10]) { Console.WriteLine(s); } } } "; var expected = @" #nullable enable class Test { void Method() { var {|Rename:array|} = new string[10]; for (var {|Rename:i|} = 0; i < array.Length; i++) { var s = array[i]; Console.WriteLine(s); } } } "; await TestInRegularAndScriptAsync(text, expected, options: ImplicitTypeEverywhere); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.ConvertForEachToFor; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertForEachToFor { public partial class ConvertForEachToForTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider( Workspace workspace, TestParameters parameters) => new CSharpConvertForEachToForCodeRefactoringProvider(); private readonly CodeStyleOption2<bool> onWithSilent = new CodeStyleOption2<bool>(true, NotificationOption2.Silent); private OptionsCollection ImplicitTypeEverywhere => new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, onWithSilent }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithSilent }, { CSharpCodeStyleOptions.VarForBuiltInTypes, onWithSilent }, }; [WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task EmptyBlockBody() { var text = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; foreach[||](var a in array) { } } } "; var expected = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; for (int {|Rename:i|} = 0; i < array.Length; i++) { int a = array[i]; } } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task EmptyBody() { var text = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; foreach[||](var a in array) ; } } "; var expected = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; for (int {|Rename:i|} = 0; i < array.Length; i++) ; } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task Body() { var text = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; foreach[||](var a in array) Console.WriteLine(a); } } "; var expected = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; for (int {|Rename:i|} = 0; i < array.Length; i++) { int a = array[i]; Console.WriteLine(a); } } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task BlockBody() { var text = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; foreach[||](var a in array) { Console.WriteLine(a); } } } "; var expected = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; for (int {|Rename:i|} = 0; i < array.Length; i++) { int a = array[i]; Console.WriteLine(a); } } } "; await TestInRegularAndScriptAsync(text, expected); } [WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task Comment() { var text = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; /* comment */ foreach[||](var a in array) /* comment */ { } } } "; var expected = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; /* comment */ for (int {|Rename:i|} = 0; i < array.Length; i++) /* comment */ { int a = array[i]; } } } "; await TestInRegularAndScriptAsync(text, expected); } [WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task Comment2() { var text = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; foreach[||](var a in array) /* comment */ { }/* comment */ } } "; var expected = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; for (int {|Rename:i|} = 0; i < array.Length; i++) /* comment */ { int a = array[i]; }/* comment */ } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task Comment3() { var text = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; foreach[||](var a in array) /* comment */; } } "; var expected = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; for (int {|Rename:i|} = 0; i < array.Length; i++) /* comment */; } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task Comment4() { var text = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; foreach[||](var a in array) Console.WriteLine(a); // test } } "; var expected = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; for (int {|Rename:i|} = 0; i < array.Length; i++) { int a = array[i]; Console.WriteLine(a); // test } } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task Comment5() { var text = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; foreach [||] (var a in array) /* test */ Console.WriteLine(a); } } "; var expected = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; for (int {|Rename:i|} = 0; i < array.Length; i++) /* test */ { int a = array[i]; Console.WriteLine(a); } } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task Comment6() { var text = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; foreach [||] (var a in array) /* test */ Console.WriteLine(a); } } "; var expected = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; for (int {|Rename:i|} = 0; i < array.Length; i++) { int a = array[i]; /* test */ Console.WriteLine(a); } } } "; await TestInRegularAndScriptAsync(text, expected); } [WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task Comment7() { var text = @" class Test { void Method() { // test foreach[||](var a in new int[] { 1, 3, 4 }) { } } } "; var expected = @" class Test { void Method() { // test int[] {|Rename:array|} = new int[] { 1, 3, 4 }; for (int {|Rename:i|} = 0; i < array.Length; i++) { int a = array[i]; } } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task TestCommentsInTheMiddleOfParentheses() { var text = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; foreach [||] (var a /* test */ in array) ; } } "; var expected = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; for (int {|Rename:i|} = 0; i < array.Length; i++) ; } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task TestCommentsAtBeginningOfParentheses() { var text = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; foreach [||] (/* test */ var a in array) ; } } "; var expected = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; for (int {|Rename:i|} = 0; i < array.Length; i++) ; } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task TestCommentsAtTheEndOfParentheses() { var text = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; foreach [||] (var a in array /* test */) ; } } "; var expected = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; for (int {|Rename:i|} = 0; i < array.Length; i++) ; } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task CollectionStatement() { var text = @" class Test { void Method() { foreach[||](var a in new int[] { 1, 3, 4 }) { Console.WriteLine(a); } } } "; var expected = @" class Test { void Method() { int[] {|Rename:array|} = new int[] { 1, 3, 4 }; for (int {|Rename:i|} = 0; i < array.Length; i++) { int a = array[i]; Console.WriteLine(a); } } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task CollectionConflict() { var text = @" class Test { void Method() { var array = 1; foreach[||](var a in new int[] { 1, 3, 4 }) { Console.WriteLine(a); } } } "; var expected = @" class Test { void Method() { var array = 1; int[] {|Rename:array1|} = new int[] { 1, 3, 4 }; for (int {|Rename:i|} = 0; i < array1.Length; i++) { int a = array1[i]; Console.WriteLine(a); } } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task VariableWritten() { var text = @" class Test { void Method() { var array = new[] { 1 }; foreach [||] (var a in array) { a = 1; } } } "; var expected = @" class Test { void Method() { var array = new[] { 1 }; for (int {|Rename:i|} = 0; i < array.Length; i++) { {|Warning:int a = array[i];|} a = 1; } } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task IndexConflict() { var text = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; foreach [||] (var a in array) { int i = 0; } } } "; var expected = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; for (int {|Rename:i1|} = 0; i1 < array.Length; i1++) { int a = array[i1]; int i = 0; } } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task StructPropertyReadFromAndDiscarded() { var text = @" class Test { struct Struct { public string Property { get; } } void Method() { var array = new[] { new Struct() }; foreach [||] (var a in array) { _ = a.Property; } } } "; var expected = @" class Test { struct Struct { public string Property { get; } } void Method() { var array = new[] { new Struct() }; for (int {|Rename:i|} = 0; i < array.Length; i++) { Struct a = array[i]; _ = a.Property; } } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task StructPropertyReadFromAndAssignedToLocal() { var text = @" class Test { struct Struct { public string Property { get; } } void Method() { var array = new[] { new Struct() }; foreach [||] (var a in array) { var b = a.Property; } } } "; var expected = @" class Test { struct Struct { public string Property { get; } } void Method() { var array = new[] { new Struct() }; for (int {|Rename:i|} = 0; i < array.Length; i++) { Struct a = array[i]; var b = a.Property; } } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task WrongCaretPosition() { var text = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; foreach (var a in array) { [||] } } } "; await TestMissingInRegularAndScriptAsync(text); } [WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task TestCaretBefore() { var text = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; [||] foreach(var a in array) { } } } "; var expected = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; for (int {|Rename:i|} = 0; i < array.Length; i++) { int a = array[i]; } } } "; await TestInRegularAndScriptAsync(text, expected); } [WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task TestCaretAfter() { var text = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; foreach(var a in array) [||] { } } } "; var expected = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; for (int {|Rename:i|} = 0; i < array.Length; i++) { int a = array[i]; } } } "; await TestInRegularAndScriptAsync(text, expected); } [WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task TestSelection() { var text = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; [|foreach(var a in array) { }|] } } "; var expected = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; for (int {|Rename:i|} = 0; i < array.Length; i++) { int a = array[i]; } } } "; await TestInRegularAndScriptAsync(text, expected); } [WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task Field() { var text = @" class Test { int[] array = new int[] { 1, 3, 4 }; void Method() { foreach [||] (var a in array) { } } } "; var expected = @" class Test { int[] array = new int[] { 1, 3, 4 }; void Method() { for (int {|Rename:i|} = 0; i < array.Length; i++) { int a = array[i]; } } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task ArrayElement() { var text = @" class Test { void Method() { var array = new int[][] { new int[] { 1, 3, 4 } }; foreach [||] (var a in array[0]) { Console.WriteLine(a); } } } "; var expected = @" class Test { void Method() { var array = new int[][] { new int[] { 1, 3, 4 } }; for (int {|Rename:i|} = 0; i < array[0].Length; i++) { int a = array[0][i]; Console.WriteLine(a); } } } "; await TestInRegularAndScriptAsync(text, expected); } [WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task Parameter() { var text = @" class Test { void Method(int[] array) { foreach [||] (var a in array) { } } } "; var expected = @" class Test { void Method(int[] array) { for (int {|Rename:i|} = 0; i < array.Length; i++) { int a = array[i]; } } } "; await TestInRegularAndScriptAsync(text, expected); } [WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task Property() { var text = @" class Test { int [] Prop { get; } = new int[] { 1, 2, 3 }; void Method() { foreach [||] (var a in Prop) { } } } "; var expected = @" class Test { int [] Prop { get; } = new int[] { 1, 2, 3 }; void Method() { for (int {|Rename:i|} = 0; i < Prop.Length; i++) { int a = Prop[i]; } } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task Interface() { var text = @" using System.Collections.Generic; class Test { void Method() { var array = (IList<int>)(new int[] { 1, 3, 4 }); foreach[||] (var a in array) { Console.WriteLine(a); } } } "; var expected = @" using System.Collections.Generic; class Test { void Method() { var array = (IList<int>)(new int[] { 1, 3, 4 }); for (int {|Rename:i|} = 0; i < array.Count; i++) { int a = array[i]; Console.WriteLine(a); } } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task IListOfT() { var text = @" using System.Collections.Generic; class Test { void Method() { var list = new List<int>(); foreach [||](var a in list) { Console.WriteLine(a); } } } "; var expected = @" using System.Collections.Generic; class Test { void Method() { var list = new List<int>(); for (int {|Rename:i|} = 0; i < list.Count; i++) { int a = list[i]; Console.WriteLine(a); } } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task IReadOnlyListOfT() { var text = @" using System.Collections; using System.Collections.Generic; class Test { void Method() { var list = new ReadOnly<int>(); foreach [||](var a in list) { Console.WriteLine(a); } } } class ReadOnly<T> : IReadOnlyList<T> { public T this[int index] => throw new System.NotImplementedException(); public int Count => throw new System.NotImplementedException(); public IEnumerator<T> GetEnumerator() => throw new System.NotImplementedException(); IEnumerator IEnumerable.GetEnumerator() => throw new System.NotImplementedException(); } "; var expected = @" using System.Collections; using System.Collections.Generic; class Test { void Method() { var list = new ReadOnly<int>(); for (int {|Rename:i|} = 0; i < list.Count; i++) { int a = list[i]; Console.WriteLine(a); } } } class ReadOnly<T> : IReadOnlyList<T> { public T this[int index] => throw new System.NotImplementedException(); public int Count => throw new System.NotImplementedException(); public IEnumerator<T> GetEnumerator() => throw new System.NotImplementedException(); IEnumerator IEnumerable.GetEnumerator() => throw new System.NotImplementedException(); } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task IList() { var text = @" using System; using System.Collections; class Test { void Method() { var list = new List(); foreach [||](var a in list) { Console.WriteLine(a); } } } class List : IList { public object this[int index] { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } public bool IsReadOnly => throw new NotImplementedException(); public bool IsFixedSize => throw new NotImplementedException(); public int Count => throw new NotImplementedException(); public object SyncRoot => throw new NotImplementedException(); public bool IsSynchronized => throw new NotImplementedException(); public int Add(object value) => throw new NotImplementedException(); public void Clear() => throw new NotImplementedException(); public bool Contains(object value) => throw new NotImplementedException(); public void CopyTo(Array array, int index) => throw new NotImplementedException(); public IEnumerator GetEnumerator() => throw new NotImplementedException(); public int IndexOf(object value) => throw new NotImplementedException(); public void Insert(int index, object value) => throw new NotImplementedException(); public void Remove(object value) => throw new NotImplementedException(); public void RemoveAt(int index) => throw new NotImplementedException(); } "; var expected = @" using System; using System.Collections; class Test { void Method() { var list = new List(); for (int {|Rename:i|} = 0; i < list.Count; i++) { object a = list[i]; Console.WriteLine(a); } } } class List : IList { public object this[int index] { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } public bool IsReadOnly => throw new NotImplementedException(); public bool IsFixedSize => throw new NotImplementedException(); public int Count => throw new NotImplementedException(); public object SyncRoot => throw new NotImplementedException(); public bool IsSynchronized => throw new NotImplementedException(); public int Add(object value) => throw new NotImplementedException(); public void Clear() => throw new NotImplementedException(); public bool Contains(object value) => throw new NotImplementedException(); public void CopyTo(Array array, int index) => throw new NotImplementedException(); public IEnumerator GetEnumerator() => throw new NotImplementedException(); public int IndexOf(object value) => throw new NotImplementedException(); public void Insert(int index, object value) => throw new NotImplementedException(); public void Remove(object value) => throw new NotImplementedException(); public void RemoveAt(int index) => throw new NotImplementedException(); } "; await TestInRegularAndScriptAsync(text, expected); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/29740"), Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task ImmutableArray() { var text = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <MetadataReference>" + typeof(ImmutableArray<>).Assembly.Location + @"</MetadataReference> <Document> using System; using System.Collections.Immutable; class Test { void Method() { var list = ImmutableArray.Create(1); foreach [||](var a in list) { Console.WriteLine(a); } } }</Document> </Project> </Workspace>"; var expected = @" using System; using System.Collections.Immutable; class Test { void Method() { var list = ImmutableArray.Create(1); for (int {|Rename:i|} = 0; i < list.Length; i++) { int a = list[i]; Console.WriteLine(a); } } }"; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task ExplicitInterface() { var text = @" using System; using System.Collections; using System.Collections.Generic; class Test { void Method() { var list = new Explicit(); foreach [||] (var a in list) { Console.WriteLine(a); } } } class Explicit : IReadOnlyList<int> { int IReadOnlyList<int>.this[int index] => throw new NotImplementedException(); int IReadOnlyCollection<int>.Count => throw new NotImplementedException(); IEnumerator<int> IEnumerable<int>.GetEnumerator() => throw new NotImplementedException(); IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException(); } "; var expected = @" using System; using System.Collections; using System.Collections.Generic; class Test { void Method() { var list = new Explicit(); IReadOnlyList<int> {|Rename:list1|} = list; for (int {|Rename:i|} = 0; i < list1.Count; i++) { int a = list1[i]; Console.WriteLine(a); } } } class Explicit : IReadOnlyList<int> { int IReadOnlyList<int>.this[int index] => throw new NotImplementedException(); int IReadOnlyCollection<int>.Count => throw new NotImplementedException(); IEnumerator<int> IEnumerable<int>.GetEnumerator() => throw new NotImplementedException(); IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException(); } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task DoubleExplicitInterface() { var text = @" using System; using System.Collections; using System.Collections.Generic; class Test { void Method() { var list = new Explicit(); foreach [||] (var a in list) { Console.WriteLine(a); } } } class Explicit : IReadOnlyList<int>, IReadOnlyList<string> { int IReadOnlyList<int>.this[int index] => throw new NotImplementedException(); int IReadOnlyCollection<int>.Count => throw new NotImplementedException(); IEnumerator<int> IEnumerable<int>.GetEnumerator() => throw new NotImplementedException(); IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException(); string IReadOnlyList<string>.this[int index] => throw new NotImplementedException(); int IReadOnlyCollection<string>.Count => throw new NotImplementedException(); IEnumerator<string> IEnumerable<string>.GetEnumerator() => throw new NotImplementedException(); } "; await TestMissingInRegularAndScriptAsync(text); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task DoubleExplicitInterfaceWithExplicitType() { var text = @" using System; using System.Collections; using System.Collections.Generic; class Test { void Method() { var list = new Explicit(); foreach [||] (int a in list) { Console.WriteLine(a); } } } class Explicit : IReadOnlyList<int>, IReadOnlyList<string> { int IReadOnlyList<int>.this[int index] => throw new NotImplementedException(); int IReadOnlyCollection<int>.Count => throw new NotImplementedException(); IEnumerator<int> IEnumerable<int>.GetEnumerator() => throw new NotImplementedException(); IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException(); string IReadOnlyList<string>.this[int index] => throw new NotImplementedException(); int IReadOnlyCollection<string>.Count => throw new NotImplementedException(); IEnumerator<string> IEnumerable<string>.GetEnumerator() => throw new NotImplementedException(); } "; var expected = @" using System; using System.Collections; using System.Collections.Generic; class Test { void Method() { var list = new Explicit(); IReadOnlyList<int> {|Rename:list1|} = list; for (int {|Rename:i|} = 0; i < list1.Count; i++) { int a = list1[i]; Console.WriteLine(a); } } } class Explicit : IReadOnlyList<int>, IReadOnlyList<string> { int IReadOnlyList<int>.this[int index] => throw new NotImplementedException(); int IReadOnlyCollection<int>.Count => throw new NotImplementedException(); IEnumerator<int> IEnumerable<int>.GetEnumerator() => throw new NotImplementedException(); IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException(); string IReadOnlyList<string>.this[int index] => throw new NotImplementedException(); int IReadOnlyCollection<string>.Count => throw new NotImplementedException(); IEnumerator<string> IEnumerable<string>.GetEnumerator() => throw new NotImplementedException(); } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task MixedInterfaceImplementation() { var text = @" using System; using System.Collections; using System.Collections.Generic; class Test { void Method() { var list = new Mixed(); foreach [||] (var a in list) { Console.WriteLine(a); } } } class Mixed : IReadOnlyList<int>, IReadOnlyList<string> { public int this[int index] => throw new NotImplementedException(); public int Count => throw new NotImplementedException(); public IEnumerator<int> GetEnumerator() => throw new NotImplementedException(); IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException(); string IReadOnlyList<string>.this[int index] => throw new NotImplementedException(); int IReadOnlyCollection<string>.Count => throw new NotImplementedException(); IEnumerator<string> IEnumerable<string>.GetEnumerator() => throw new NotImplementedException(); } "; var expected = @" using System; using System.Collections; using System.Collections.Generic; class Test { void Method() { var list = new Mixed(); for (int {|Rename:i|} = 0; i < list.Count; i++) { int a = list[i]; Console.WriteLine(a); } } } class Mixed : IReadOnlyList<int>, IReadOnlyList<string> { public int this[int index] => throw new NotImplementedException(); public int Count => throw new NotImplementedException(); public IEnumerator<int> GetEnumerator() => throw new NotImplementedException(); IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException(); string IReadOnlyList<string>.this[int index] => throw new NotImplementedException(); int IReadOnlyCollection<string>.Count => throw new NotImplementedException(); IEnumerator<string> IEnumerable<string>.GetEnumerator() => throw new NotImplementedException(); } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task MixedInterfaceImplementationWithExplicitType() { var text = @" using System; using System.Collections; using System.Collections.Generic; class Test { void Method() { var list = new Mixed(); foreach [||] (string a in list) { Console.WriteLine(a); } } } class Mixed : IReadOnlyList<int>, IReadOnlyList<string> { public int this[int index] => throw new NotImplementedException(); public int Count => throw new NotImplementedException(); public IEnumerator<int> GetEnumerator() => throw new NotImplementedException(); IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException(); string IReadOnlyList<string>.this[int index] => throw new NotImplementedException(); int IReadOnlyCollection<string>.Count => throw new NotImplementedException(); IEnumerator<string> IEnumerable<string>.GetEnumerator() => throw new NotImplementedException(); } "; var expected = @" using System; using System.Collections; using System.Collections.Generic; class Test { void Method() { var list = new Mixed(); IReadOnlyList<string> {|Rename:list1|} = list; for (int {|Rename:i|} = 0; i < list1.Count; i++) { string a = list1[i]; Console.WriteLine(a); } } } class Mixed : IReadOnlyList<int>, IReadOnlyList<string> { public int this[int index] => throw new NotImplementedException(); public int Count => throw new NotImplementedException(); public IEnumerator<int> GetEnumerator() => throw new NotImplementedException(); IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException(); string IReadOnlyList<string>.this[int index] => throw new NotImplementedException(); int IReadOnlyCollection<string>.Count => throw new NotImplementedException(); IEnumerator<string> IEnumerable<string>.GetEnumerator() => throw new NotImplementedException(); } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task PreserveUserExpression() { var text = @" using System; using System.Collections; using System.Collections.Generic; namespace NS { class Test { void Method() { foreach [||] (string a in new NS.Mixed()) { Console.WriteLine(a); } } } class Mixed : IReadOnlyList<int>, IReadOnlyList<string> { public int this[int index] => throw new NotImplementedException(); public int Count => throw new NotImplementedException(); public IEnumerator<int> GetEnumerator() => throw new NotImplementedException(); IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException(); string IReadOnlyList<string>.this[int index] => throw new NotImplementedException(); int IReadOnlyCollection<string>.Count => throw new NotImplementedException(); IEnumerator<string> IEnumerable<string>.GetEnumerator() => throw new NotImplementedException(); } } "; var expected = @" using System; using System.Collections; using System.Collections.Generic; namespace NS { class Test { void Method() { IReadOnlyList<string> {|Rename:list|} = new NS.Mixed(); for (int {|Rename:i|} = 0; i < list.Count; i++) { string a = list[i]; Console.WriteLine(a); } } } class Mixed : IReadOnlyList<int>, IReadOnlyList<string> { public int this[int index] => throw new NotImplementedException(); public int Count => throw new NotImplementedException(); public IEnumerator<int> GetEnumerator() => throw new NotImplementedException(); IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException(); string IReadOnlyList<string>.this[int index] => throw new NotImplementedException(); int IReadOnlyCollection<string>.Count => throw new NotImplementedException(); IEnumerator<string> IEnumerable<string>.GetEnumerator() => throw new NotImplementedException(); } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task EmbededStatement() { var text = @" class Test { void Method() { if (true) foreach [||] (var a in new int[] {}); } } "; await TestMissingInRegularAndScriptAsync(text); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task EmbededStatement2() { var text = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; if (true) foreach [||] (var a in array) Console.WriteLine(a); } } "; var expected = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; if (true) for (int {|Rename:i|} = 0; i < array.Length; i++) { int a = array[i]; Console.WriteLine(a); } } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task IndexConflict2() { var text = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; foreach [||] (var i in array) { Console.WriteLine(i); } } } "; var expected = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; for (int {|Rename:i1|} = 0; i1 < array.Length; i1++) { int i = array[i1]; Console.WriteLine(i); } } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task UseTypeAsUsedInForeach() { var text = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; foreach [||] (int a in array) { Console.WriteLine(i); } } } "; var expected = @" class Test { void Method() { var array = new int[] { 1, 3, 4 }; for (int {|Rename:i|} = 0; i < array.Length; i++) { int a = array[i]; Console.WriteLine(i); } } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task String() { var text = @" class Test { void Method() { foreach [||] (var a in ""test"") { Console.WriteLine(a); } } } "; var expected = @" class Test { void Method() { string {|Rename:str|} = ""test""; for (int {|Rename:i|} = 0; i < str.Length; i++) { char a = str[i]; Console.WriteLine(a); } } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task StringLocalConst() { var text = @" class Test { void Method() { const string test = ""test""; foreach [||] (var a in test) { Console.WriteLine(a); } } } "; var expected = @" class Test { void Method() { const string test = ""test""; for (int {|Rename:i|} = 0; i < test.Length; i++) { char a = test[i]; Console.WriteLine(a); } } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task StringConst() { var text = @" class Test { const string test = ""test""; void Method() { foreach [||] (var a in test) { Console.WriteLine(a); } } } "; var expected = @" class Test { const string test = ""test""; void Method() { for (int {|Rename:i|} = 0; i < test.Length; i++) { char a = test[i]; Console.WriteLine(a); } } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task ElementExplicitCast() { var text = @" class Test { void Method() { var array = new object[] { 1, 2, 3 }; foreach [||] (string a in array) { Console.WriteLine(a); } } } "; var expected = @" class Test { void Method() { var array = new object[] { 1, 2, 3 }; for (int {|Rename:i|} = 0; i < array.Length; i++) { string a = (string)array[i]; Console.WriteLine(a); } } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task NotAssignable() { var text = @" class Test { void Method() { var array = new int[] { 1, 2, 3 }; foreach [||] (string a in array) { Console.WriteLine(a); } } } "; await TestMissingInRegularAndScriptAsync(text); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task ElementMissing() { var text = @" class Test { void Method() { var array = new int[] { 1, 2, 3 }; foreach [||] (in array) { Console.WriteLine(a); } } } "; await TestMissingInRegularAndScriptAsync(text); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task ElementMissing2() { var text = @" class Test { void Method() { foreach [||] (string a in ) { Console.WriteLine(a); } } } "; await TestMissingInRegularAndScriptAsync(text); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task StringExplicitType() { var text = @" class Test { void Method() { foreach [||] (int a in ""test"") { Console.WriteLine(a); } } } "; var expected = @" class Test { void Method() { string {|Rename:str|} = ""test""; for (int {|Rename:i|} = 0; i < str.Length; i++) { int a = str[i]; Console.WriteLine(a); } } } "; await TestInRegularAndScriptAsync(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task Var() { var text = @" using System; using System.Collections; using System.Collections.Generic; class Test { void Method() { var list = new Explicit(); foreach [||] (var a in list) { Console.WriteLine(a); } } } class Explicit : IReadOnlyList<int> { int IReadOnlyList<int>.this[int index] => throw new NotImplementedException(); int IReadOnlyCollection<int>.Count => throw new NotImplementedException(); IEnumerator<int> IEnumerable<int>.GetEnumerator() => throw new NotImplementedException(); IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException(); } "; var expected = @" using System; using System.Collections; using System.Collections.Generic; class Test { void Method() { var list = new Explicit(); var {|Rename:list1|} = (IReadOnlyList<int>)list; for (var {|Rename:i|} = 0; i < list1.Count; i++) { var a = list1[i]; Console.WriteLine(a); } } } class Explicit : IReadOnlyList<int> { int IReadOnlyList<int>.this[int index] => throw new NotImplementedException(); int IReadOnlyCollection<int>.Count => throw new NotImplementedException(); IEnumerator<int> IEnumerable<int>.GetEnumerator() => throw new NotImplementedException(); IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException(); } "; await TestInRegularAndScriptAsync(text, expected, options: ImplicitTypeEverywhere); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task ArrayRank2() { var text = @" class Test { void Method() { foreach [||] (int a in new int[,] { {1, 2} }) { Console.WriteLine(a); } } } "; await TestMissingAsync(text); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] [WorkItem(48950, "https://github.com/dotnet/roslyn/issues/48950")] public async Task NullableReferenceVar() { var text = @" #nullable enable class Test { void Method() { foreach [||] (var s in new string[10]) { Console.WriteLine(s); } } } "; var expected = @" #nullable enable class Test { void Method() { var {|Rename:array|} = new string[10]; for (var {|Rename:i|} = 0; i < array.Length; i++) { var s = array[i]; Console.WriteLine(s); } } } "; await TestInRegularAndScriptAsync(text, expected, options: ImplicitTypeEverywhere); } } }
-1
dotnet/roslyn
55,419
Make vsix's compatible with vs 2022
Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
dibarbet
2021-08-04T23:36:41Z
2021-08-06T17:54:08Z
082df2aaf6a73277fc27f9d7a5a8d18ee45d7f8b
e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028
Make vsix's compatible with vs 2022. Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
./src/VisualStudio/VisualStudioDiagnosticsToolWindow/OptionPages/PerformanceLoggersPage.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Remote; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices; using Microsoft.VisualStudio.LanguageServices.Implementation; using Microsoft.VisualStudio.LanguageServices.Implementation.Options; namespace Roslyn.VisualStudio.DiagnosticsWindow.OptionsPages { [Guid(Guids.RoslynOptionPagePerformanceLoggersIdString)] internal class PerformanceLoggersPage : AbstractOptionPage { private IGlobalOptionService _optionService; private IThreadingContext _threadingContext; private IRemoteHostClientProvider _remoteClientProvider; protected override AbstractOptionPageControl CreateOptionPage(IServiceProvider serviceProvider, OptionStore optionStore) { if (_optionService == null) { var componentModel = (IComponentModel)serviceProvider.GetService(typeof(SComponentModel)); _optionService = componentModel.GetService<IGlobalOptionService>(); _threadingContext = componentModel.GetService<IThreadingContext>(); var workspace = componentModel.GetService<VisualStudioWorkspace>(); _remoteClientProvider = workspace.Services.GetService<IRemoteHostClientProvider>(); } return new InternalOptionsControl(nameof(LoggerOptions), optionStore); } protected override void OnApply(PageApplyEventArgs e) { base.OnApply(e); SetLoggers(_optionService, _threadingContext, _remoteClientProvider); } public static void SetLoggers(IGlobalOptionService optionService, IThreadingContext threadingContext, IRemoteHostClientProvider remoteClientProvider) { var loggerTypes = GetLoggerTypes(optionService).ToList(); // first set VS options var options = Logger.GetLoggingChecker(optionService); SetRoslynLogger(loggerTypes, () => new EtwLogger(options)); SetRoslynLogger(loggerTypes, () => new TraceLogger(options)); SetRoslynLogger(loggerTypes, () => new OutputWindowLogger(options)); // second set RemoteHost options var client = threadingContext.JoinableTaskFactory.Run(() => remoteClientProvider.TryGetRemoteHostClientAsync(CancellationToken.None)); if (client == null) { // Remote host is disabled return; } var functionIds = GetFunctionIds(options).ToList(); threadingContext.JoinableTaskFactory.Run(() => client.RunRemoteAsync( WellKnownServiceHubService.RemoteHost, nameof(IRemoteHostService.SetLoggingFunctionIds), solution: null, new object[] { loggerTypes, functionIds }, callbackTarget: null, CancellationToken.None)); } private static IEnumerable<string> GetFunctionIds(Func<FunctionId, bool> options) { foreach (var functionId in Enum.GetValues(typeof(FunctionId)).Cast<FunctionId>()) { if (options(functionId)) { yield return functionId.ToString(); } } } private static IEnumerable<string> GetLoggerTypes(IGlobalOptionService optionService) { if (optionService.GetOption(LoggerOptions.EtwLoggerKey)) { yield return nameof(EtwLogger); } if (optionService.GetOption(LoggerOptions.TraceLoggerKey)) { yield return nameof(TraceLogger); } if (optionService.GetOption(LoggerOptions.OutputWindowLoggerKey)) { yield return nameof(OutputWindowLogger); } } private static void SetRoslynLogger<T>(List<string> loggerTypes, Func<T> creator) where T : ILogger { if (loggerTypes.Contains(typeof(T).Name)) { Logger.SetLogger(AggregateLogger.AddOrReplace(creator(), Logger.GetLogger(), l => l is T)); } else { Logger.SetLogger(AggregateLogger.Remove(Logger.GetLogger(), l => l is T)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Remote; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices; using Microsoft.VisualStudio.LanguageServices.Implementation; using Microsoft.VisualStudio.LanguageServices.Implementation.Options; namespace Roslyn.VisualStudio.DiagnosticsWindow.OptionsPages { [Guid(Guids.RoslynOptionPagePerformanceLoggersIdString)] internal class PerformanceLoggersPage : AbstractOptionPage { private IGlobalOptionService _optionService; private IThreadingContext _threadingContext; private IRemoteHostClientProvider _remoteClientProvider; protected override AbstractOptionPageControl CreateOptionPage(IServiceProvider serviceProvider, OptionStore optionStore) { if (_optionService == null) { var componentModel = (IComponentModel)serviceProvider.GetService(typeof(SComponentModel)); _optionService = componentModel.GetService<IGlobalOptionService>(); _threadingContext = componentModel.GetService<IThreadingContext>(); var workspace = componentModel.GetService<VisualStudioWorkspace>(); _remoteClientProvider = workspace.Services.GetService<IRemoteHostClientProvider>(); } return new InternalOptionsControl(nameof(LoggerOptions), optionStore); } protected override void OnApply(PageApplyEventArgs e) { base.OnApply(e); SetLoggers(_optionService, _threadingContext, _remoteClientProvider); } public static void SetLoggers(IGlobalOptionService optionService, IThreadingContext threadingContext, IRemoteHostClientProvider remoteClientProvider) { var loggerTypes = GetLoggerTypes(optionService).ToList(); // first set VS options var options = Logger.GetLoggingChecker(optionService); SetRoslynLogger(loggerTypes, () => new EtwLogger(options)); SetRoslynLogger(loggerTypes, () => new TraceLogger(options)); SetRoslynLogger(loggerTypes, () => new OutputWindowLogger(options)); // second set RemoteHost options var client = threadingContext.JoinableTaskFactory.Run(() => remoteClientProvider.TryGetRemoteHostClientAsync(CancellationToken.None)); if (client == null) { // Remote host is disabled return; } var functionIds = GetFunctionIds(options).ToList(); threadingContext.JoinableTaskFactory.Run(() => client.RunRemoteAsync( WellKnownServiceHubService.RemoteHost, nameof(IRemoteHostService.SetLoggingFunctionIds), solution: null, new object[] { loggerTypes, functionIds }, callbackTarget: null, CancellationToken.None)); } private static IEnumerable<string> GetFunctionIds(Func<FunctionId, bool> options) { foreach (var functionId in Enum.GetValues(typeof(FunctionId)).Cast<FunctionId>()) { if (options(functionId)) { yield return functionId.ToString(); } } } private static IEnumerable<string> GetLoggerTypes(IGlobalOptionService optionService) { if (optionService.GetOption(LoggerOptions.EtwLoggerKey)) { yield return nameof(EtwLogger); } if (optionService.GetOption(LoggerOptions.TraceLoggerKey)) { yield return nameof(TraceLogger); } if (optionService.GetOption(LoggerOptions.OutputWindowLoggerKey)) { yield return nameof(OutputWindowLogger); } } private static void SetRoslynLogger<T>(List<string> loggerTypes, Func<T> creator) where T : ILogger { if (loggerTypes.Contains(typeof(T).Name)) { Logger.SetLogger(AggregateLogger.AddOrReplace(creator(), Logger.GetLogger(), l => l is T)); } else { Logger.SetLogger(AggregateLogger.Remove(Logger.GetLogger(), l => l is T)); } } } }
-1
dotnet/roslyn
55,419
Make vsix's compatible with vs 2022
Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
dibarbet
2021-08-04T23:36:41Z
2021-08-06T17:54:08Z
082df2aaf6a73277fc27f9d7a5a8d18ee45d7f8b
e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028
Make vsix's compatible with vs 2022. Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
./src/Compilers/Core/MSBuildTaskTests/TargetTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // uncomment the below define to dump binlogs of each test //#define DUMP_MSBUILD_BIN_LOG using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Xml; using Roslyn.Test.Utilities; using Microsoft.Build.Evaluation; using Microsoft.Build.Execution; using Microsoft.Build.Framework; using Xunit; namespace Microsoft.CodeAnalysis.BuildTasks.UnitTests { public class TargetTests : TestBase { [Fact] public void GenerateEditorConfigShouldNotRunWhenNoPropertiesOrMetadata() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFileShouldRun", GetTestLoggers()); var shouldRun = instance.GetPropertyValue("_GeneratedEditorConfigShouldRun"); var hasItems = instance.GetPropertyValue("_GeneratedEditorConfigHasItems"); Assert.True(runSuccess); Assert.NotEqual("true", shouldRun); Assert.NotEqual("true", hasItems); } [Fact] public void GenerateEditorConfigShouldRunWhenPropertiesRequested() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <ItemGroup> <CompilerVisibleProperty Include=""prop"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFileShouldRun", GetTestLoggers()); var shouldRun = instance.GetPropertyValue("_GeneratedEditorConfigShouldRun"); var hasItems = instance.GetPropertyValue("_GeneratedEditorConfigHasItems"); Assert.True(runSuccess); Assert.Equal("true", shouldRun); Assert.NotEqual("true", hasItems); } [Fact] public void GenerateEditorConfigShouldRunWhenMetadataRequested() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <ItemGroup> <CompilerVisibleItemMetadata Include=""item"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFileShouldRun", GetTestLoggers()); var shouldRun = instance.GetPropertyValue("_GeneratedEditorConfigShouldRun"); var hasItems = instance.GetPropertyValue("_GeneratedEditorConfigHasItems"); Assert.True(runSuccess); Assert.Equal("true", shouldRun); Assert.Equal("true", hasItems); } [Fact] public void GenerateEditorConfigShouldRunWhenPropertiesAndMetadata() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <ItemGroup> <CompilerVisibleProperty Include=""prop"" /> <CompilerVisibleItemMetadata Include=""item"" MetadataName=""meta"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFileShouldRun", GetTestLoggers()); var shouldRun = instance.GetPropertyValue("_GeneratedEditorConfigShouldRun"); var hasItems = instance.GetPropertyValue("_GeneratedEditorConfigHasItems"); Assert.True(runSuccess); Assert.Equal("true", shouldRun); Assert.Equal("true", hasItems); } [Fact] public void GenerateEditorConfigCanBeDisabled() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <PropertyGroup> <GenerateMSBuildEditorConfigFile>false</GenerateMSBuildEditorConfigFile> </PropertyGroup> <ItemGroup> <CompilerVisibleProperty Include=""prop"" /> <CompilerVisibleItemMetadata Include=""item"" MetadataName=""meta"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFileShouldRun", GetTestLoggers()); var shouldRun = instance.GetPropertyValue("_GeneratedEditorConfigShouldRun"); var hasItems = instance.GetPropertyValue("_GeneratedEditorConfigHasItems"); Assert.True(runSuccess); Assert.NotEqual("true", shouldRun); Assert.Equal("true", hasItems); } [Fact] public void GenerateEditorConfigCoreEvaluatesProperties() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <PropertyGroup> <ValueToGet>abc</ValueToGet> </PropertyGroup> <ItemGroup> <CompilerVisibleProperty Include=""ValueToGet"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFile", GetTestLoggers()); Assert.True(runSuccess); var items = instance.GetItems("_GeneratedEditorConfigProperty"); Assert.Single(items); var item = items.Single(); Assert.Equal("_GeneratedEditorConfigProperty", item.ItemType); Assert.Single(item.Metadata); var metadata = item.Metadata.Single(); Assert.Equal("Value", metadata.Name); Assert.Equal("abc", metadata.EvaluatedValue); } [Fact] public void GenerateEditorConfigCoreEvaluatesDynamicProperties() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <PropertyGroup> <RealValue>def</RealValue> <ValueToGet>$(RealValue)</ValueToGet> </PropertyGroup> <ItemGroup> <CompilerVisibleProperty Include=""ValueToGet"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFile", GetTestLoggers()); Assert.True(runSuccess); var items = instance.GetItems("_GeneratedEditorConfigProperty"); Assert.Single(items); var item = items.Single(); Assert.Equal("_GeneratedEditorConfigProperty", item.ItemType); Assert.Single(item.Metadata); var metadata = item.Metadata.Single(); Assert.Equal("Value", metadata.Name); Assert.Equal("def", metadata.EvaluatedValue); } [Fact] public void GenerateEditorConfigCoreHandlesMissingProperties() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <ItemGroup> <CompilerVisibleProperty Include=""ValueToGet"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFile", GetTestLoggers()); Assert.True(runSuccess); var items = instance.GetItems("_GeneratedEditorConfigProperty"); Assert.Single(items); var item = items.Single(); Assert.Equal("_GeneratedEditorConfigProperty", item.ItemType); Assert.Single(item.Metadata); var metadata = item.Metadata.Single(); Assert.Equal("Value", metadata.Name); Assert.Equal("", metadata.EvaluatedValue); } [Fact] public void GenerateEditorConfigCoreEvaluatesMetadata() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <ItemGroup> <Compile Include=""file1.cs"" CustomMeta=""abc"" /> </ItemGroup> <ItemGroup> <CompilerVisibleItemMetadata Include=""Compile"" MetadataName=""CustomMeta"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFile", GetTestLoggers()); Assert.True(runSuccess); var items = instance.GetItems("_GeneratedEditorConfigMetadata"); Assert.Single(items); var item = items.Single(); Assert.Equal("_GeneratedEditorConfigMetadata", item.ItemType); var itemType = item.Metadata.SingleOrDefault(m => m.Name == "ItemType"); AssertEx.NotNull(itemType); Assert.Equal("Compile", itemType.EvaluatedValue); var metaName = item.Metadata.SingleOrDefault(m => m.Name == "MetadataName"); AssertEx.NotNull(metaName); Assert.Equal("CustomMeta", metaName.EvaluatedValue); var customMeta = item.Metadata.SingleOrDefault(m => m.Name == metaName.EvaluatedValue); AssertEx.NotNull(customMeta); Assert.Equal("abc", customMeta.EvaluatedValue); } [Fact] public void GenerateEditorConfigCoreEvaluatesDynamicMetadata() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <PropertyGroup> <DynamicValue>abc</DynamicValue> </PropertyGroup> <ItemGroup> <Compile Include=""file1.cs"" CustomMeta=""$(DynamicValue)"" /> </ItemGroup> <ItemGroup> <CompilerVisibleItemMetadata Include=""Compile"" MetadataName=""CustomMeta"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFile", GetTestLoggers()); Assert.True(runSuccess); var items = instance.GetItems("_GeneratedEditorConfigMetadata"); Assert.Single(items); var item = items.Single(); Assert.Equal("_GeneratedEditorConfigMetadata", item.ItemType); var itemType = item.Metadata.SingleOrDefault(m => m.Name == "ItemType"); AssertEx.NotNull(itemType); Assert.Equal("Compile", itemType.EvaluatedValue); var metaName = item.Metadata.SingleOrDefault(m => m.Name == "MetadataName"); AssertEx.NotNull(metaName); Assert.Equal("CustomMeta", metaName.EvaluatedValue); var customMeta = item.Metadata.SingleOrDefault(m => m.Name == metaName.EvaluatedValue); AssertEx.NotNull(customMeta); Assert.Equal("abc", customMeta.EvaluatedValue); } [Fact] public void GenerateEditorConfigCoreHandlesMissingMetadata() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <ItemGroup> <Compile Include=""file1.cs"" /> </ItemGroup> <ItemGroup> <CompilerVisibleItemMetadata Include=""Compile"" MetadataName=""CustomMeta"" /> <CompilerVisibleItemMetadata Include=""Compile2"" MetadataName=""CustomMeta"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFile", GetTestLoggers()); Assert.True(runSuccess); var items = instance.GetItems("_GeneratedEditorConfigMetadata"); Assert.Single(items); var item = items.Single(); Assert.Equal("_GeneratedEditorConfigMetadata", item.ItemType); var itemType = item.Metadata.SingleOrDefault(m => m.Name == "ItemType"); AssertEx.NotNull(itemType); Assert.Equal("Compile", itemType.EvaluatedValue); var metaName = item.Metadata.SingleOrDefault(m => m.Name == "MetadataName"); AssertEx.NotNull(metaName); Assert.Equal("CustomMeta", metaName.EvaluatedValue); } [Fact] public void GenerateEditorConfigCoreHandlesMalformedCompilerVisibleItemMetadata() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <ItemGroup> <Compile Include=""file1.cs"" /> </ItemGroup> <ItemGroup> <CompilerVisibleItemMetadata Include=""Compile"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFile", GetTestLoggers()); Assert.True(runSuccess); var items = instance.GetItems("_GeneratedEditorConfigMetadata"); Assert.Single(items); var item = items.Single(); Assert.Equal("_GeneratedEditorConfigMetadata", item.ItemType); var itemType = item.Metadata.SingleOrDefault(m => m.Name == "ItemType"); AssertEx.NotNull(itemType); Assert.Equal("Compile", itemType.EvaluatedValue); var metaName = item.Metadata.SingleOrDefault(m => m.Name == "MetadataName"); AssertEx.NotNull(metaName); Assert.Equal("", metaName.EvaluatedValue); } [Theory] [InlineData(".NETFramework", "4.5", "7.3")] [InlineData(".NETFramework", "4.7.2", "7.3")] [InlineData(".NETFramework", "4.8", "7.3")] [InlineData(".NETCoreApp", "1.0", "7.3")] [InlineData(".NETCoreApp", "2.0", "7.3")] [InlineData(".NETCoreApp", "2.1", "7.3")] [InlineData(".NETCoreApp", "3.0", "8.0")] [InlineData(".NETCoreApp", "3.1", "8.0")] [InlineData(".NETCoreApp", "5.0", "9.0")] [InlineData(".NETCoreApp", "6.0", "10.0")] [InlineData(".NETCoreApp", "7.0", "")] [InlineData(".NETStandard", "1.0", "7.3")] [InlineData(".NETStandard", "1.5", "7.3")] [InlineData(".NETStandard", "2.0", "7.3")] [InlineData(".NETStandard", "2.1", "8.0")] [InlineData("UnknownTFM", "0.0", "7.3")] [InlineData("UnknownTFM", "5.0", "7.3")] [InlineData("UnknownTFM", "6.0", "7.3")] public void LanguageVersionGivenTargetFramework(string tfi, string tfv, string expectedVersion) { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <PropertyGroup> <TargetFrameworkIdentifier>{tfi}</TargetFrameworkIdentifier> <_TargetFrameworkVersionWithoutV>{tfv}</_TargetFrameworkVersionWithoutV> </PropertyGroup> <Import Project=""Microsoft.CSharp.Core.targets"" /> </Project> ")); var instance = CreateProjectInstance(xmlReader); instance.Build(GetTestLoggers()); var langVersion = instance.GetPropertyValue("LangVersion"); var maxLangVersion = instance.GetPropertyValue("_MaxSupportedLangVersion"); Assert.Equal(expectedVersion, langVersion); Assert.Equal(expectedVersion, maxLangVersion); // This will fail whenever the current language version is updated. // Ensure you update the target files to select the correct CSharp version for the newest target framework // and add to the theory data above to cover it, before changing this version to make the test pass again. Assert.Equal(CSharp.LanguageVersion.CSharp10, CSharp.LanguageVersionFacts.CurrentVersion); } [Fact] public void ExplicitLangVersion() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <PropertyGroup> <TargetFrameworkIdentifier>.NETCoreApp</TargetFrameworkIdentifier> <_TargetFrameworkVersionWithoutV>2.0</_TargetFrameworkVersionWithoutV> <LangVersion>55.0</LangVersion> </PropertyGroup> <Import Project=""Microsoft.CSharp.Core.targets"" /> </Project> ")); var instance = CreateProjectInstance(xmlReader); instance.Build(GetTestLoggers()); var langVersion = instance.GetPropertyValue("LangVersion"); var maxLangVersion = instance.GetPropertyValue("_MaxSupportedLangVersion"); Assert.Equal("55.0", langVersion); Assert.Equal("7.3", maxLangVersion); } [Fact] public void MaxSupportedLangVersionIsReadable() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <PropertyGroup> <TargetFrameworkIdentifier>.NETCoreApp</TargetFrameworkIdentifier> <_TargetFrameworkVersionWithoutV>2.0</_TargetFrameworkVersionWithoutV> <LangVersion>9.0</LangVersion> </PropertyGroup> <Import Project=""Microsoft.CSharp.Core.targets"" /> </Project> ")); var instance = CreateProjectInstance(xmlReader); instance.Build(GetTestLoggers()); var langVersion = instance.GetPropertyValue("LangVersion"); var maxLangVersion = instance.GetPropertyValue("_MaxSupportedLangVersion"); var publicMaxLangVersion = instance.GetPropertyValue("MaxSupportedLangVersion"); Assert.Equal("9.0", langVersion); Assert.Equal("7.3", maxLangVersion); Assert.Equal("7.3", publicMaxLangVersion); } [Fact] public void MaxSupportedLangVersionIsnotWriteable() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <PropertyGroup> <TargetFrameworkIdentifier>.NETCoreApp</TargetFrameworkIdentifier> <_TargetFrameworkVersionWithoutV>2.0</_TargetFrameworkVersionWithoutV> <LangVersion>9.0</LangVersion> <MaxSupportedLangVersion>9.0</MaxSupportedLangVersion> </PropertyGroup> <Import Project=""Microsoft.CSharp.Core.targets"" /> </Project> ")); var instance = CreateProjectInstance(xmlReader); instance.Build(GetTestLoggers()); var langVersion = instance.GetPropertyValue("LangVersion"); var maxLangVersion = instance.GetPropertyValue("_MaxSupportedLangVersion"); var publicMaxLangVersion = instance.GetPropertyValue("MaxSupportedLangVersion"); Assert.Equal("9.0", langVersion); Assert.Equal("7.3", maxLangVersion); Assert.Equal("7.3", publicMaxLangVersion); } [Fact] public void GenerateEditorConfigIsPassedToTheCompiler() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <ItemGroup> <CompilerVisibleProperty Include=""prop"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFile", GetTestLoggers()); Assert.True(runSuccess); var items = instance.GetItems("EditorConfigFiles"); Assert.Single(items); } [Fact] public void AdditionalFilesAreAddedToNoneWhenCopied() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <ItemGroup> <AdditionalFiles Include=""file1.cs"" CopyToOutputDirectory=""Always"" /> <AdditionalFiles Include=""file2.cs"" CopyToOutputDirectory=""PreserveNewest"" /> <AdditionalFiles Include=""file3.cs"" CopyToOutputDirectory=""Never"" /> <AdditionalFiles Include=""file4.cs"" CopyToOutputDirectory="""" /> <AdditionalFiles Include=""file5.cs"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "CopyAdditionalFiles", GetTestLoggers()); Assert.True(runSuccess); var noneItems = instance.GetItems("None").ToArray(); Assert.Equal(3, noneItems.Length); Assert.Equal("file1.cs", noneItems[0].EvaluatedInclude); Assert.Equal("Always", noneItems[0].GetMetadataValue("CopyToOutputDirectory")); Assert.Equal("file2.cs", noneItems[1].EvaluatedInclude); Assert.Equal("PreserveNewest", noneItems[1].GetMetadataValue("CopyToOutputDirectory")); Assert.Equal("file3.cs", noneItems[2].EvaluatedInclude); Assert.Equal("Never", noneItems[2].GetMetadataValue("CopyToOutputDirectory")); } [Fact] public void GeneratedFilesOutputPathHasDefaults() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> </Project> ")); var instance = CreateProjectInstance(xmlReader); var emit = instance.GetPropertyValue("EmitCompilerGeneratedFiles"); var dir = instance.GetPropertyValue("CompilerGeneratedFilesOutputPath"); Assert.Equal("false", emit); Assert.Equal(string.Empty, dir); } [Fact] public void GeneratedFilesOutputPathDefaultsToIntermediateOutputPathWhenSet() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <PropertyGroup> <IntermediateOutputPath>fallbackDirectory</IntermediateOutputPath> <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles> </PropertyGroup> <Import Project=""Microsoft.Managed.Core.targets"" /> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "CreateCompilerGeneratedFilesOutputPath", GetTestLoggers()); Assert.True(runSuccess); var emit = instance.GetPropertyValue("EmitCompilerGeneratedFiles"); var dir = instance.GetPropertyValue("CompilerGeneratedFilesOutputPath"); Assert.Equal("true", emit); Assert.Equal("fallbackDirectory/generated", dir); } [Fact] public void GeneratedFilesOutputPathDefaultsIsEmptyWhenEmitDisable() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <PropertyGroup> <EmitCompilerGeneratedFiles>false</EmitCompilerGeneratedFiles> <IntermediateOutputPath>fallbackDirectory</IntermediateOutputPath> </PropertyGroup> <Import Project=""Microsoft.Managed.Core.targets"" /> </Project> ")); var instance = CreateProjectInstance(xmlReader); var emit = instance.GetPropertyValue("EmitCompilerGeneratedFiles"); var dir = instance.GetPropertyValue("CompilerGeneratedFilesOutputPath"); Assert.Equal("false", emit); Assert.Equal(string.Empty, dir); } [Theory] [InlineData(true, "generatedDirectory")] [InlineData(true, null)] [InlineData(false, "generatedDirectory")] [InlineData(false, null)] public void GeneratedFilesOutputPathCanBeSetAndSuppressed(bool emitGeneratedFiles, string? generatedFilesDir) { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <PropertyGroup> <EmitCompilerGeneratedFiles>{(emitGeneratedFiles.ToString().ToLower())}</EmitCompilerGeneratedFiles> <CompilerGeneratedFilesOutputPath>{generatedFilesDir}</CompilerGeneratedFilesOutputPath> <IntermediateOutputPath>fallbackDirectory</IntermediateOutputPath> </PropertyGroup> <Import Project=""Microsoft.Managed.Core.targets"" /> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "CreateCompilerGeneratedFilesOutputPath", GetTestLoggers()); Assert.True(runSuccess); var emit = instance.GetPropertyValue("EmitCompilerGeneratedFiles"); var dir = instance.GetPropertyValue("CompilerGeneratedFilesOutputPath"); Assert.Equal(emitGeneratedFiles.ToString().ToLower(), emit); if (emitGeneratedFiles) { string expectedDir = generatedFilesDir ?? "fallbackDirectory/generated"; Assert.Equal(expectedDir, dir); } else { Assert.Equal(string.Empty, dir); } } [Theory, CombinatorialData] [WorkItem(40926, "https://github.com/dotnet/roslyn/issues/40926")] public void TestSkipAnalyzers( [CombinatorialValues(true, false, null)] bool? runAnalyzers, [CombinatorialValues(true, false, null)] bool? runAnalyzersDuringBuild) { var runAnalyzersPropertyGroupString = getPropertyGroup("RunAnalyzers", runAnalyzers); var runAnalyzersDuringBuildPropertyGroupString = getPropertyGroup("RunAnalyzersDuringBuild", runAnalyzersDuringBuild); XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> {runAnalyzersPropertyGroupString} {runAnalyzersDuringBuildPropertyGroupString} </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "_ComputeSkipAnalyzers", GetTestLoggers()); Assert.True(runSuccess); // Verify "RunAnalyzers" overrides "RunAnalyzersDuringBuild". // If neither properties are set, analyzers are enabled by default. var analyzersEnabled = runAnalyzers ?? runAnalyzersDuringBuild ?? true; var expectedSkipAnalyzersValue = !analyzersEnabled ? "true" : ""; var actualSkipAnalyzersValue = instance.GetPropertyValue("_SkipAnalyzers"); Assert.Equal(expectedSkipAnalyzersValue, actualSkipAnalyzersValue); return; static string getPropertyGroup(string propertyName, bool? propertyValue) { if (!propertyValue.HasValue) { return string.Empty; } return $@" <PropertyGroup> <{propertyName}>{propertyValue.Value}</{propertyName}> </PropertyGroup>"; } } [Theory, CombinatorialData] [WorkItem(1337109, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1337109")] public void TestImplicitlySkipAnalyzers( [CombinatorialValues(true, false, null)] bool? runAnalyzers, [CombinatorialValues(true, false, null)] bool? implicitBuild, [CombinatorialValues(true, false, null)] bool? treatWarningsAsErrors, [CombinatorialValues(true, false, null)] bool? optimizeImplicitBuild, [CombinatorialValues(true, null)] bool? sdkStyleProject) { var runAnalyzersPropertyGroupString = getPropertyGroup("RunAnalyzers", runAnalyzers); var implicitBuildPropertyGroupString = getPropertyGroup("IsImplicitlyTriggeredBuild", implicitBuild); var treatWarningsAsErrorsPropertyGroupString = getPropertyGroup("TreatWarningsAsErrors", treatWarningsAsErrors); var optimizeImplicitBuildPropertyGroupString = getPropertyGroup("OptimizeImplicitlyTriggeredBuild", optimizeImplicitBuild); var sdkStyleProjectPropertyGroupString = getPropertyGroup("UsingMicrosoftNETSdk", sdkStyleProject); XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> {runAnalyzersPropertyGroupString} {implicitBuildPropertyGroupString} {treatWarningsAsErrorsPropertyGroupString} {optimizeImplicitBuildPropertyGroupString} {sdkStyleProjectPropertyGroupString} </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "_ComputeSkipAnalyzers", GetTestLoggers()); Assert.True(runSuccess); var analyzersEnabled = runAnalyzers ?? true; var expectedImplicitlySkippedAnalyzers = analyzersEnabled && implicitBuild == true && sdkStyleProject == true && (treatWarningsAsErrors != true || optimizeImplicitBuild == true); var expectedImplicitlySkippedAnalyzersValue = expectedImplicitlySkippedAnalyzers ? "true" : ""; var actualImplicitlySkippedAnalyzersValue = instance.GetPropertyValue("_ImplicitlySkipAnalyzers"); Assert.Equal(expectedImplicitlySkippedAnalyzersValue, actualImplicitlySkippedAnalyzersValue); var expectedSkipAnalyzersValue = !analyzersEnabled || expectedImplicitlySkippedAnalyzers ? "true" : ""; var actualSkipAnalyzersValue = instance.GetPropertyValue("_SkipAnalyzers"); Assert.Equal(expectedSkipAnalyzersValue, actualSkipAnalyzersValue); var expectedFeaturesValue = expectedImplicitlySkippedAnalyzers ? "run-nullable-analysis=never;" : ""; var actualFeaturesValue = instance.GetPropertyValue("Features"); Assert.Equal(expectedFeaturesValue, actualFeaturesValue); return; static string getPropertyGroup(string propertyName, bool? propertyValue) { if (!propertyValue.HasValue) { return string.Empty; } return $@" <PropertyGroup> <{propertyName}>{propertyValue.Value}</{propertyName}> </PropertyGroup>"; } } [Theory, CombinatorialData] [WorkItem(1337109, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1337109")] public void TestLastBuildWithSkipAnalyzers( [CombinatorialValues(true, false, null)] bool? runAnalyzers, bool lastBuildWithSkipAnalyzersFileExists) { var runAnalyzersPropertyGroupString = getPropertyGroup("RunAnalyzers", runAnalyzers); var intermediatePathDir = Temp.CreateDirectory(); var intermediatePath = intermediatePathDir + Path.DirectorySeparatorChar.ToString(); XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> {runAnalyzersPropertyGroupString} <PropertyGroup> <IntermediateOutputPath>{intermediatePath}</IntermediateOutputPath> </PropertyGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); var msbuildProjectFileName = instance.GetPropertyValue("MSBuildProjectFile"); var expectedLastBuildWithSkipAnalyzers = intermediatePath + msbuildProjectFileName + ".BuildWithSkipAnalyzers"; if (lastBuildWithSkipAnalyzersFileExists) { _ = intermediatePathDir.CreateFile(msbuildProjectFileName + ".BuildWithSkipAnalyzers"); } bool runSuccess = instance.Build(target: "_ComputeSkipAnalyzers", GetTestLoggers()); Assert.True(runSuccess); var actualLastBuildWithSkipAnalyzers = instance.GetPropertyValue("_LastBuildWithSkipAnalyzers"); Assert.Equal(expectedLastBuildWithSkipAnalyzers, actualLastBuildWithSkipAnalyzers); var skipAnalyzers = !(runAnalyzers ?? true); var expectedCustomAdditionalCompileInput = lastBuildWithSkipAnalyzersFileExists && !skipAnalyzers; var items = instance.GetItems("CustomAdditionalCompileInputs"); var expectedItemCount = expectedCustomAdditionalCompileInput ? 1 : 0; Assert.Equal(expectedItemCount, items.Count); if (expectedCustomAdditionalCompileInput) { Assert.Equal(expectedLastBuildWithSkipAnalyzers, items.Single().EvaluatedInclude); } var expectedUpToDateCheckInput = lastBuildWithSkipAnalyzersFileExists; items = instance.GetItems("UpToDateCheckInput"); expectedItemCount = expectedUpToDateCheckInput ? 1 : 0; Assert.Equal(expectedItemCount, items.Count); if (expectedUpToDateCheckInput) { var item = items.Single(); Assert.Equal(expectedLastBuildWithSkipAnalyzers, item.EvaluatedInclude); Assert.Equal("ImplicitBuild", item.GetMetadataValue("Kind")); } return; static string getPropertyGroup(string propertyName, bool? propertyValue) { if (!propertyValue.HasValue) { return string.Empty; } return $@" <PropertyGroup> <{propertyName}>{propertyValue.Value}</{propertyName}> </PropertyGroup>"; } } [Fact] public void ProjectCapabilityIsNotAddedWhenRoslynComponentIsUnspecified() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> </Project> ")); var instance = CreateProjectInstance(xmlReader); var caps = instance.GetItems("ProjectCapability").Select(c => c.EvaluatedInclude); Assert.DoesNotContain("RoslynComponent", caps); } [Fact] public void ProjectCapabilityIsAddedWhenRoslynComponentSpecified() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <PropertyGroup> <IsRoslynComponent>true</IsRoslynComponent> </PropertyGroup> <Import Project=""Microsoft.Managed.Core.targets"" /> </Project> ")); var instance = CreateProjectInstance(xmlReader); var caps = instance.GetItems("ProjectCapability").Select(c => c.EvaluatedInclude); Assert.Contains("RoslynComponent", caps); } private static ProjectInstance CreateProjectInstance(XmlReader reader) { Project proj = new Project(reader); // add a dummy prepare for build target proj.Xml.AddTarget("PrepareForBuild"); // create a dummy WriteLinesToFile task addTask(proj, "WriteLinesToFile", new() { { "Lines", "System.String[]" }, { "File", "System.String" }, { "Overwrite", "System.Boolean" }, { "WriteOnlyWhenDifferent", "System.Boolean" } }); // dummy makeDir task addTask(proj, "MakeDir", new() { { "Directories", "System.String[]" } }); // dummy Message task addTask(proj, "Message", new() { { "Text", "System.String" }, { "Importance", "System.String" } }); // create an instance and return it return proj.CreateProjectInstance(); static void addTask(Project proj, string taskName, Dictionary<string, string> parameters) { var task = proj.Xml.AddUsingTask(taskName, string.Empty, Assembly.GetExecutingAssembly().FullName); task.TaskFactory = nameof(DummyTaskFactory); var taskParams = task.AddParameterGroup(); foreach (var kvp in parameters) { taskParams.AddParameter(kvp.Key, string.Empty, string.Empty, kvp.Value); } } } private static ILogger[] GetTestLoggers([CallerMemberName] string callerName = "") { #if DUMP_MSBUILD_BIN_LOG return new ILogger[] { new Build.Logging.BinaryLogger() { Parameters = callerName + ".binlog" } }; #else return Array.Empty<ILogger>(); #endif } } /// <summary> /// Task factory that creates empty tasks for testing /// </summary> /// <remarks> /// Replace any task with a dummy task by adding a <c>UsingTask</c> /// <code> /// <UsingTask TaskName="[TaskToReplace]" TaskFactory="DummyTaskFactory"> /// <ParameterGroup> /// <Param1 ParameterType="[Type]" /> /// </ParameterGroup> /// </UsingTask> /// </code> /// /// You can specify the parameters the task should have via a <c>ParameterGroup</c> /// These should match the task you are replacing. /// </remarks> public sealed class DummyTaskFactory : ITaskFactory { public string FactoryName { get => "DummyTaskFactory"; } public Type TaskType { get => typeof(DummyTaskFactory); } private TaskPropertyInfo[]? _props; public void CleanupTask(ITask task) { } public ITask CreateTask(IBuildEngine taskFactoryLoggingHost) => new DummyTask(); public TaskPropertyInfo[]? GetTaskParameters() => _props; public bool Initialize(string taskName, IDictionary<string, TaskPropertyInfo> parameterGroup, string taskBody, IBuildEngine taskFactoryLoggingHost) { _props = parameterGroup.Values.ToArray(); return true; } private class DummyTask : IGeneratedTask { public IBuildEngine? BuildEngine { get; set; } public ITaskHost? HostObject { get; set; } public bool Execute() => true; public object GetPropertyValue(TaskPropertyInfo property) => null!; public void SetPropertyValue(TaskPropertyInfo property, object value) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // uncomment the below define to dump binlogs of each test //#define DUMP_MSBUILD_BIN_LOG using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Xml; using Roslyn.Test.Utilities; using Microsoft.Build.Evaluation; using Microsoft.Build.Execution; using Microsoft.Build.Framework; using Xunit; namespace Microsoft.CodeAnalysis.BuildTasks.UnitTests { public class TargetTests : TestBase { [Fact] public void GenerateEditorConfigShouldNotRunWhenNoPropertiesOrMetadata() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFileShouldRun", GetTestLoggers()); var shouldRun = instance.GetPropertyValue("_GeneratedEditorConfigShouldRun"); var hasItems = instance.GetPropertyValue("_GeneratedEditorConfigHasItems"); Assert.True(runSuccess); Assert.NotEqual("true", shouldRun); Assert.NotEqual("true", hasItems); } [Fact] public void GenerateEditorConfigShouldRunWhenPropertiesRequested() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <ItemGroup> <CompilerVisibleProperty Include=""prop"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFileShouldRun", GetTestLoggers()); var shouldRun = instance.GetPropertyValue("_GeneratedEditorConfigShouldRun"); var hasItems = instance.GetPropertyValue("_GeneratedEditorConfigHasItems"); Assert.True(runSuccess); Assert.Equal("true", shouldRun); Assert.NotEqual("true", hasItems); } [Fact] public void GenerateEditorConfigShouldRunWhenMetadataRequested() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <ItemGroup> <CompilerVisibleItemMetadata Include=""item"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFileShouldRun", GetTestLoggers()); var shouldRun = instance.GetPropertyValue("_GeneratedEditorConfigShouldRun"); var hasItems = instance.GetPropertyValue("_GeneratedEditorConfigHasItems"); Assert.True(runSuccess); Assert.Equal("true", shouldRun); Assert.Equal("true", hasItems); } [Fact] public void GenerateEditorConfigShouldRunWhenPropertiesAndMetadata() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <ItemGroup> <CompilerVisibleProperty Include=""prop"" /> <CompilerVisibleItemMetadata Include=""item"" MetadataName=""meta"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFileShouldRun", GetTestLoggers()); var shouldRun = instance.GetPropertyValue("_GeneratedEditorConfigShouldRun"); var hasItems = instance.GetPropertyValue("_GeneratedEditorConfigHasItems"); Assert.True(runSuccess); Assert.Equal("true", shouldRun); Assert.Equal("true", hasItems); } [Fact] public void GenerateEditorConfigCanBeDisabled() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <PropertyGroup> <GenerateMSBuildEditorConfigFile>false</GenerateMSBuildEditorConfigFile> </PropertyGroup> <ItemGroup> <CompilerVisibleProperty Include=""prop"" /> <CompilerVisibleItemMetadata Include=""item"" MetadataName=""meta"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFileShouldRun", GetTestLoggers()); var shouldRun = instance.GetPropertyValue("_GeneratedEditorConfigShouldRun"); var hasItems = instance.GetPropertyValue("_GeneratedEditorConfigHasItems"); Assert.True(runSuccess); Assert.NotEqual("true", shouldRun); Assert.Equal("true", hasItems); } [Fact] public void GenerateEditorConfigCoreEvaluatesProperties() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <PropertyGroup> <ValueToGet>abc</ValueToGet> </PropertyGroup> <ItemGroup> <CompilerVisibleProperty Include=""ValueToGet"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFile", GetTestLoggers()); Assert.True(runSuccess); var items = instance.GetItems("_GeneratedEditorConfigProperty"); Assert.Single(items); var item = items.Single(); Assert.Equal("_GeneratedEditorConfigProperty", item.ItemType); Assert.Single(item.Metadata); var metadata = item.Metadata.Single(); Assert.Equal("Value", metadata.Name); Assert.Equal("abc", metadata.EvaluatedValue); } [Fact] public void GenerateEditorConfigCoreEvaluatesDynamicProperties() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <PropertyGroup> <RealValue>def</RealValue> <ValueToGet>$(RealValue)</ValueToGet> </PropertyGroup> <ItemGroup> <CompilerVisibleProperty Include=""ValueToGet"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFile", GetTestLoggers()); Assert.True(runSuccess); var items = instance.GetItems("_GeneratedEditorConfigProperty"); Assert.Single(items); var item = items.Single(); Assert.Equal("_GeneratedEditorConfigProperty", item.ItemType); Assert.Single(item.Metadata); var metadata = item.Metadata.Single(); Assert.Equal("Value", metadata.Name); Assert.Equal("def", metadata.EvaluatedValue); } [Fact] public void GenerateEditorConfigCoreHandlesMissingProperties() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <ItemGroup> <CompilerVisibleProperty Include=""ValueToGet"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFile", GetTestLoggers()); Assert.True(runSuccess); var items = instance.GetItems("_GeneratedEditorConfigProperty"); Assert.Single(items); var item = items.Single(); Assert.Equal("_GeneratedEditorConfigProperty", item.ItemType); Assert.Single(item.Metadata); var metadata = item.Metadata.Single(); Assert.Equal("Value", metadata.Name); Assert.Equal("", metadata.EvaluatedValue); } [Fact] public void GenerateEditorConfigCoreEvaluatesMetadata() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <ItemGroup> <Compile Include=""file1.cs"" CustomMeta=""abc"" /> </ItemGroup> <ItemGroup> <CompilerVisibleItemMetadata Include=""Compile"" MetadataName=""CustomMeta"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFile", GetTestLoggers()); Assert.True(runSuccess); var items = instance.GetItems("_GeneratedEditorConfigMetadata"); Assert.Single(items); var item = items.Single(); Assert.Equal("_GeneratedEditorConfigMetadata", item.ItemType); var itemType = item.Metadata.SingleOrDefault(m => m.Name == "ItemType"); AssertEx.NotNull(itemType); Assert.Equal("Compile", itemType.EvaluatedValue); var metaName = item.Metadata.SingleOrDefault(m => m.Name == "MetadataName"); AssertEx.NotNull(metaName); Assert.Equal("CustomMeta", metaName.EvaluatedValue); var customMeta = item.Metadata.SingleOrDefault(m => m.Name == metaName.EvaluatedValue); AssertEx.NotNull(customMeta); Assert.Equal("abc", customMeta.EvaluatedValue); } [Fact] public void GenerateEditorConfigCoreEvaluatesDynamicMetadata() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <PropertyGroup> <DynamicValue>abc</DynamicValue> </PropertyGroup> <ItemGroup> <Compile Include=""file1.cs"" CustomMeta=""$(DynamicValue)"" /> </ItemGroup> <ItemGroup> <CompilerVisibleItemMetadata Include=""Compile"" MetadataName=""CustomMeta"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFile", GetTestLoggers()); Assert.True(runSuccess); var items = instance.GetItems("_GeneratedEditorConfigMetadata"); Assert.Single(items); var item = items.Single(); Assert.Equal("_GeneratedEditorConfigMetadata", item.ItemType); var itemType = item.Metadata.SingleOrDefault(m => m.Name == "ItemType"); AssertEx.NotNull(itemType); Assert.Equal("Compile", itemType.EvaluatedValue); var metaName = item.Metadata.SingleOrDefault(m => m.Name == "MetadataName"); AssertEx.NotNull(metaName); Assert.Equal("CustomMeta", metaName.EvaluatedValue); var customMeta = item.Metadata.SingleOrDefault(m => m.Name == metaName.EvaluatedValue); AssertEx.NotNull(customMeta); Assert.Equal("abc", customMeta.EvaluatedValue); } [Fact] public void GenerateEditorConfigCoreHandlesMissingMetadata() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <ItemGroup> <Compile Include=""file1.cs"" /> </ItemGroup> <ItemGroup> <CompilerVisibleItemMetadata Include=""Compile"" MetadataName=""CustomMeta"" /> <CompilerVisibleItemMetadata Include=""Compile2"" MetadataName=""CustomMeta"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFile", GetTestLoggers()); Assert.True(runSuccess); var items = instance.GetItems("_GeneratedEditorConfigMetadata"); Assert.Single(items); var item = items.Single(); Assert.Equal("_GeneratedEditorConfigMetadata", item.ItemType); var itemType = item.Metadata.SingleOrDefault(m => m.Name == "ItemType"); AssertEx.NotNull(itemType); Assert.Equal("Compile", itemType.EvaluatedValue); var metaName = item.Metadata.SingleOrDefault(m => m.Name == "MetadataName"); AssertEx.NotNull(metaName); Assert.Equal("CustomMeta", metaName.EvaluatedValue); } [Fact] public void GenerateEditorConfigCoreHandlesMalformedCompilerVisibleItemMetadata() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <ItemGroup> <Compile Include=""file1.cs"" /> </ItemGroup> <ItemGroup> <CompilerVisibleItemMetadata Include=""Compile"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFile", GetTestLoggers()); Assert.True(runSuccess); var items = instance.GetItems("_GeneratedEditorConfigMetadata"); Assert.Single(items); var item = items.Single(); Assert.Equal("_GeneratedEditorConfigMetadata", item.ItemType); var itemType = item.Metadata.SingleOrDefault(m => m.Name == "ItemType"); AssertEx.NotNull(itemType); Assert.Equal("Compile", itemType.EvaluatedValue); var metaName = item.Metadata.SingleOrDefault(m => m.Name == "MetadataName"); AssertEx.NotNull(metaName); Assert.Equal("", metaName.EvaluatedValue); } [Theory] [InlineData(".NETFramework", "4.5", "7.3")] [InlineData(".NETFramework", "4.7.2", "7.3")] [InlineData(".NETFramework", "4.8", "7.3")] [InlineData(".NETCoreApp", "1.0", "7.3")] [InlineData(".NETCoreApp", "2.0", "7.3")] [InlineData(".NETCoreApp", "2.1", "7.3")] [InlineData(".NETCoreApp", "3.0", "8.0")] [InlineData(".NETCoreApp", "3.1", "8.0")] [InlineData(".NETCoreApp", "5.0", "9.0")] [InlineData(".NETCoreApp", "6.0", "10.0")] [InlineData(".NETCoreApp", "7.0", "")] [InlineData(".NETStandard", "1.0", "7.3")] [InlineData(".NETStandard", "1.5", "7.3")] [InlineData(".NETStandard", "2.0", "7.3")] [InlineData(".NETStandard", "2.1", "8.0")] [InlineData("UnknownTFM", "0.0", "7.3")] [InlineData("UnknownTFM", "5.0", "7.3")] [InlineData("UnknownTFM", "6.0", "7.3")] public void LanguageVersionGivenTargetFramework(string tfi, string tfv, string expectedVersion) { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <PropertyGroup> <TargetFrameworkIdentifier>{tfi}</TargetFrameworkIdentifier> <_TargetFrameworkVersionWithoutV>{tfv}</_TargetFrameworkVersionWithoutV> </PropertyGroup> <Import Project=""Microsoft.CSharp.Core.targets"" /> </Project> ")); var instance = CreateProjectInstance(xmlReader); instance.Build(GetTestLoggers()); var langVersion = instance.GetPropertyValue("LangVersion"); var maxLangVersion = instance.GetPropertyValue("_MaxSupportedLangVersion"); Assert.Equal(expectedVersion, langVersion); Assert.Equal(expectedVersion, maxLangVersion); // This will fail whenever the current language version is updated. // Ensure you update the target files to select the correct CSharp version for the newest target framework // and add to the theory data above to cover it, before changing this version to make the test pass again. Assert.Equal(CSharp.LanguageVersion.CSharp10, CSharp.LanguageVersionFacts.CurrentVersion); } [Fact] public void ExplicitLangVersion() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <PropertyGroup> <TargetFrameworkIdentifier>.NETCoreApp</TargetFrameworkIdentifier> <_TargetFrameworkVersionWithoutV>2.0</_TargetFrameworkVersionWithoutV> <LangVersion>55.0</LangVersion> </PropertyGroup> <Import Project=""Microsoft.CSharp.Core.targets"" /> </Project> ")); var instance = CreateProjectInstance(xmlReader); instance.Build(GetTestLoggers()); var langVersion = instance.GetPropertyValue("LangVersion"); var maxLangVersion = instance.GetPropertyValue("_MaxSupportedLangVersion"); Assert.Equal("55.0", langVersion); Assert.Equal("7.3", maxLangVersion); } [Fact] public void MaxSupportedLangVersionIsReadable() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <PropertyGroup> <TargetFrameworkIdentifier>.NETCoreApp</TargetFrameworkIdentifier> <_TargetFrameworkVersionWithoutV>2.0</_TargetFrameworkVersionWithoutV> <LangVersion>9.0</LangVersion> </PropertyGroup> <Import Project=""Microsoft.CSharp.Core.targets"" /> </Project> ")); var instance = CreateProjectInstance(xmlReader); instance.Build(GetTestLoggers()); var langVersion = instance.GetPropertyValue("LangVersion"); var maxLangVersion = instance.GetPropertyValue("_MaxSupportedLangVersion"); var publicMaxLangVersion = instance.GetPropertyValue("MaxSupportedLangVersion"); Assert.Equal("9.0", langVersion); Assert.Equal("7.3", maxLangVersion); Assert.Equal("7.3", publicMaxLangVersion); } [Fact] public void MaxSupportedLangVersionIsnotWriteable() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <PropertyGroup> <TargetFrameworkIdentifier>.NETCoreApp</TargetFrameworkIdentifier> <_TargetFrameworkVersionWithoutV>2.0</_TargetFrameworkVersionWithoutV> <LangVersion>9.0</LangVersion> <MaxSupportedLangVersion>9.0</MaxSupportedLangVersion> </PropertyGroup> <Import Project=""Microsoft.CSharp.Core.targets"" /> </Project> ")); var instance = CreateProjectInstance(xmlReader); instance.Build(GetTestLoggers()); var langVersion = instance.GetPropertyValue("LangVersion"); var maxLangVersion = instance.GetPropertyValue("_MaxSupportedLangVersion"); var publicMaxLangVersion = instance.GetPropertyValue("MaxSupportedLangVersion"); Assert.Equal("9.0", langVersion); Assert.Equal("7.3", maxLangVersion); Assert.Equal("7.3", publicMaxLangVersion); } [Fact] public void GenerateEditorConfigIsPassedToTheCompiler() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <ItemGroup> <CompilerVisibleProperty Include=""prop"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "GenerateMSBuildEditorConfigFile", GetTestLoggers()); Assert.True(runSuccess); var items = instance.GetItems("EditorConfigFiles"); Assert.Single(items); } [Fact] public void AdditionalFilesAreAddedToNoneWhenCopied() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> <ItemGroup> <AdditionalFiles Include=""file1.cs"" CopyToOutputDirectory=""Always"" /> <AdditionalFiles Include=""file2.cs"" CopyToOutputDirectory=""PreserveNewest"" /> <AdditionalFiles Include=""file3.cs"" CopyToOutputDirectory=""Never"" /> <AdditionalFiles Include=""file4.cs"" CopyToOutputDirectory="""" /> <AdditionalFiles Include=""file5.cs"" /> </ItemGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "CopyAdditionalFiles", GetTestLoggers()); Assert.True(runSuccess); var noneItems = instance.GetItems("None").ToArray(); Assert.Equal(3, noneItems.Length); Assert.Equal("file1.cs", noneItems[0].EvaluatedInclude); Assert.Equal("Always", noneItems[0].GetMetadataValue("CopyToOutputDirectory")); Assert.Equal("file2.cs", noneItems[1].EvaluatedInclude); Assert.Equal("PreserveNewest", noneItems[1].GetMetadataValue("CopyToOutputDirectory")); Assert.Equal("file3.cs", noneItems[2].EvaluatedInclude); Assert.Equal("Never", noneItems[2].GetMetadataValue("CopyToOutputDirectory")); } [Fact] public void GeneratedFilesOutputPathHasDefaults() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> </Project> ")); var instance = CreateProjectInstance(xmlReader); var emit = instance.GetPropertyValue("EmitCompilerGeneratedFiles"); var dir = instance.GetPropertyValue("CompilerGeneratedFilesOutputPath"); Assert.Equal("false", emit); Assert.Equal(string.Empty, dir); } [Fact] public void GeneratedFilesOutputPathDefaultsToIntermediateOutputPathWhenSet() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <PropertyGroup> <IntermediateOutputPath>fallbackDirectory</IntermediateOutputPath> <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles> </PropertyGroup> <Import Project=""Microsoft.Managed.Core.targets"" /> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "CreateCompilerGeneratedFilesOutputPath", GetTestLoggers()); Assert.True(runSuccess); var emit = instance.GetPropertyValue("EmitCompilerGeneratedFiles"); var dir = instance.GetPropertyValue("CompilerGeneratedFilesOutputPath"); Assert.Equal("true", emit); Assert.Equal("fallbackDirectory/generated", dir); } [Fact] public void GeneratedFilesOutputPathDefaultsIsEmptyWhenEmitDisable() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <PropertyGroup> <EmitCompilerGeneratedFiles>false</EmitCompilerGeneratedFiles> <IntermediateOutputPath>fallbackDirectory</IntermediateOutputPath> </PropertyGroup> <Import Project=""Microsoft.Managed.Core.targets"" /> </Project> ")); var instance = CreateProjectInstance(xmlReader); var emit = instance.GetPropertyValue("EmitCompilerGeneratedFiles"); var dir = instance.GetPropertyValue("CompilerGeneratedFilesOutputPath"); Assert.Equal("false", emit); Assert.Equal(string.Empty, dir); } [Theory] [InlineData(true, "generatedDirectory")] [InlineData(true, null)] [InlineData(false, "generatedDirectory")] [InlineData(false, null)] public void GeneratedFilesOutputPathCanBeSetAndSuppressed(bool emitGeneratedFiles, string? generatedFilesDir) { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <PropertyGroup> <EmitCompilerGeneratedFiles>{(emitGeneratedFiles.ToString().ToLower())}</EmitCompilerGeneratedFiles> <CompilerGeneratedFilesOutputPath>{generatedFilesDir}</CompilerGeneratedFilesOutputPath> <IntermediateOutputPath>fallbackDirectory</IntermediateOutputPath> </PropertyGroup> <Import Project=""Microsoft.Managed.Core.targets"" /> </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "CreateCompilerGeneratedFilesOutputPath", GetTestLoggers()); Assert.True(runSuccess); var emit = instance.GetPropertyValue("EmitCompilerGeneratedFiles"); var dir = instance.GetPropertyValue("CompilerGeneratedFilesOutputPath"); Assert.Equal(emitGeneratedFiles.ToString().ToLower(), emit); if (emitGeneratedFiles) { string expectedDir = generatedFilesDir ?? "fallbackDirectory/generated"; Assert.Equal(expectedDir, dir); } else { Assert.Equal(string.Empty, dir); } } [Theory, CombinatorialData] [WorkItem(40926, "https://github.com/dotnet/roslyn/issues/40926")] public void TestSkipAnalyzers( [CombinatorialValues(true, false, null)] bool? runAnalyzers, [CombinatorialValues(true, false, null)] bool? runAnalyzersDuringBuild) { var runAnalyzersPropertyGroupString = getPropertyGroup("RunAnalyzers", runAnalyzers); var runAnalyzersDuringBuildPropertyGroupString = getPropertyGroup("RunAnalyzersDuringBuild", runAnalyzersDuringBuild); XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> {runAnalyzersPropertyGroupString} {runAnalyzersDuringBuildPropertyGroupString} </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "_ComputeSkipAnalyzers", GetTestLoggers()); Assert.True(runSuccess); // Verify "RunAnalyzers" overrides "RunAnalyzersDuringBuild". // If neither properties are set, analyzers are enabled by default. var analyzersEnabled = runAnalyzers ?? runAnalyzersDuringBuild ?? true; var expectedSkipAnalyzersValue = !analyzersEnabled ? "true" : ""; var actualSkipAnalyzersValue = instance.GetPropertyValue("_SkipAnalyzers"); Assert.Equal(expectedSkipAnalyzersValue, actualSkipAnalyzersValue); return; static string getPropertyGroup(string propertyName, bool? propertyValue) { if (!propertyValue.HasValue) { return string.Empty; } return $@" <PropertyGroup> <{propertyName}>{propertyValue.Value}</{propertyName}> </PropertyGroup>"; } } [Theory, CombinatorialData] [WorkItem(1337109, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1337109")] public void TestImplicitlySkipAnalyzers( [CombinatorialValues(true, false, null)] bool? runAnalyzers, [CombinatorialValues(true, false, null)] bool? implicitBuild, [CombinatorialValues(true, false, null)] bool? treatWarningsAsErrors, [CombinatorialValues(true, false, null)] bool? optimizeImplicitBuild, [CombinatorialValues(true, null)] bool? sdkStyleProject) { var runAnalyzersPropertyGroupString = getPropertyGroup("RunAnalyzers", runAnalyzers); var implicitBuildPropertyGroupString = getPropertyGroup("IsImplicitlyTriggeredBuild", implicitBuild); var treatWarningsAsErrorsPropertyGroupString = getPropertyGroup("TreatWarningsAsErrors", treatWarningsAsErrors); var optimizeImplicitBuildPropertyGroupString = getPropertyGroup("OptimizeImplicitlyTriggeredBuild", optimizeImplicitBuild); var sdkStyleProjectPropertyGroupString = getPropertyGroup("UsingMicrosoftNETSdk", sdkStyleProject); XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> {runAnalyzersPropertyGroupString} {implicitBuildPropertyGroupString} {treatWarningsAsErrorsPropertyGroupString} {optimizeImplicitBuildPropertyGroupString} {sdkStyleProjectPropertyGroupString} </Project> ")); var instance = CreateProjectInstance(xmlReader); bool runSuccess = instance.Build(target: "_ComputeSkipAnalyzers", GetTestLoggers()); Assert.True(runSuccess); var analyzersEnabled = runAnalyzers ?? true; var expectedImplicitlySkippedAnalyzers = analyzersEnabled && implicitBuild == true && sdkStyleProject == true && (treatWarningsAsErrors != true || optimizeImplicitBuild == true); var expectedImplicitlySkippedAnalyzersValue = expectedImplicitlySkippedAnalyzers ? "true" : ""; var actualImplicitlySkippedAnalyzersValue = instance.GetPropertyValue("_ImplicitlySkipAnalyzers"); Assert.Equal(expectedImplicitlySkippedAnalyzersValue, actualImplicitlySkippedAnalyzersValue); var expectedSkipAnalyzersValue = !analyzersEnabled || expectedImplicitlySkippedAnalyzers ? "true" : ""; var actualSkipAnalyzersValue = instance.GetPropertyValue("_SkipAnalyzers"); Assert.Equal(expectedSkipAnalyzersValue, actualSkipAnalyzersValue); var expectedFeaturesValue = expectedImplicitlySkippedAnalyzers ? "run-nullable-analysis=never;" : ""; var actualFeaturesValue = instance.GetPropertyValue("Features"); Assert.Equal(expectedFeaturesValue, actualFeaturesValue); return; static string getPropertyGroup(string propertyName, bool? propertyValue) { if (!propertyValue.HasValue) { return string.Empty; } return $@" <PropertyGroup> <{propertyName}>{propertyValue.Value}</{propertyName}> </PropertyGroup>"; } } [Theory, CombinatorialData] [WorkItem(1337109, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1337109")] public void TestLastBuildWithSkipAnalyzers( [CombinatorialValues(true, false, null)] bool? runAnalyzers, bool lastBuildWithSkipAnalyzersFileExists) { var runAnalyzersPropertyGroupString = getPropertyGroup("RunAnalyzers", runAnalyzers); var intermediatePathDir = Temp.CreateDirectory(); var intermediatePath = intermediatePathDir + Path.DirectorySeparatorChar.ToString(); XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> {runAnalyzersPropertyGroupString} <PropertyGroup> <IntermediateOutputPath>{intermediatePath}</IntermediateOutputPath> </PropertyGroup> </Project> ")); var instance = CreateProjectInstance(xmlReader); var msbuildProjectFileName = instance.GetPropertyValue("MSBuildProjectFile"); var expectedLastBuildWithSkipAnalyzers = intermediatePath + msbuildProjectFileName + ".BuildWithSkipAnalyzers"; if (lastBuildWithSkipAnalyzersFileExists) { _ = intermediatePathDir.CreateFile(msbuildProjectFileName + ".BuildWithSkipAnalyzers"); } bool runSuccess = instance.Build(target: "_ComputeSkipAnalyzers", GetTestLoggers()); Assert.True(runSuccess); var actualLastBuildWithSkipAnalyzers = instance.GetPropertyValue("_LastBuildWithSkipAnalyzers"); Assert.Equal(expectedLastBuildWithSkipAnalyzers, actualLastBuildWithSkipAnalyzers); var skipAnalyzers = !(runAnalyzers ?? true); var expectedCustomAdditionalCompileInput = lastBuildWithSkipAnalyzersFileExists && !skipAnalyzers; var items = instance.GetItems("CustomAdditionalCompileInputs"); var expectedItemCount = expectedCustomAdditionalCompileInput ? 1 : 0; Assert.Equal(expectedItemCount, items.Count); if (expectedCustomAdditionalCompileInput) { Assert.Equal(expectedLastBuildWithSkipAnalyzers, items.Single().EvaluatedInclude); } var expectedUpToDateCheckInput = lastBuildWithSkipAnalyzersFileExists; items = instance.GetItems("UpToDateCheckInput"); expectedItemCount = expectedUpToDateCheckInput ? 1 : 0; Assert.Equal(expectedItemCount, items.Count); if (expectedUpToDateCheckInput) { var item = items.Single(); Assert.Equal(expectedLastBuildWithSkipAnalyzers, item.EvaluatedInclude); Assert.Equal("ImplicitBuild", item.GetMetadataValue("Kind")); } return; static string getPropertyGroup(string propertyName, bool? propertyValue) { if (!propertyValue.HasValue) { return string.Empty; } return $@" <PropertyGroup> <{propertyName}>{propertyValue.Value}</{propertyName}> </PropertyGroup>"; } } [Fact] public void ProjectCapabilityIsNotAddedWhenRoslynComponentIsUnspecified() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <Import Project=""Microsoft.Managed.Core.targets"" /> </Project> ")); var instance = CreateProjectInstance(xmlReader); var caps = instance.GetItems("ProjectCapability").Select(c => c.EvaluatedInclude); Assert.DoesNotContain("RoslynComponent", caps); } [Fact] public void ProjectCapabilityIsAddedWhenRoslynComponentSpecified() { XmlReader xmlReader = XmlReader.Create(new StringReader($@" <Project> <PropertyGroup> <IsRoslynComponent>true</IsRoslynComponent> </PropertyGroup> <Import Project=""Microsoft.Managed.Core.targets"" /> </Project> ")); var instance = CreateProjectInstance(xmlReader); var caps = instance.GetItems("ProjectCapability").Select(c => c.EvaluatedInclude); Assert.Contains("RoslynComponent", caps); } private static ProjectInstance CreateProjectInstance(XmlReader reader) { Project proj = new Project(reader); // add a dummy prepare for build target proj.Xml.AddTarget("PrepareForBuild"); // create a dummy WriteLinesToFile task addTask(proj, "WriteLinesToFile", new() { { "Lines", "System.String[]" }, { "File", "System.String" }, { "Overwrite", "System.Boolean" }, { "WriteOnlyWhenDifferent", "System.Boolean" } }); // dummy makeDir task addTask(proj, "MakeDir", new() { { "Directories", "System.String[]" } }); // dummy Message task addTask(proj, "Message", new() { { "Text", "System.String" }, { "Importance", "System.String" } }); // create an instance and return it return proj.CreateProjectInstance(); static void addTask(Project proj, string taskName, Dictionary<string, string> parameters) { var task = proj.Xml.AddUsingTask(taskName, string.Empty, Assembly.GetExecutingAssembly().FullName); task.TaskFactory = nameof(DummyTaskFactory); var taskParams = task.AddParameterGroup(); foreach (var kvp in parameters) { taskParams.AddParameter(kvp.Key, string.Empty, string.Empty, kvp.Value); } } } private static ILogger[] GetTestLoggers([CallerMemberName] string callerName = "") { #if DUMP_MSBUILD_BIN_LOG return new ILogger[] { new Build.Logging.BinaryLogger() { Parameters = callerName + ".binlog" } }; #else return Array.Empty<ILogger>(); #endif } } /// <summary> /// Task factory that creates empty tasks for testing /// </summary> /// <remarks> /// Replace any task with a dummy task by adding a <c>UsingTask</c> /// <code> /// <UsingTask TaskName="[TaskToReplace]" TaskFactory="DummyTaskFactory"> /// <ParameterGroup> /// <Param1 ParameterType="[Type]" /> /// </ParameterGroup> /// </UsingTask> /// </code> /// /// You can specify the parameters the task should have via a <c>ParameterGroup</c> /// These should match the task you are replacing. /// </remarks> public sealed class DummyTaskFactory : ITaskFactory { public string FactoryName { get => "DummyTaskFactory"; } public Type TaskType { get => typeof(DummyTaskFactory); } private TaskPropertyInfo[]? _props; public void CleanupTask(ITask task) { } public ITask CreateTask(IBuildEngine taskFactoryLoggingHost) => new DummyTask(); public TaskPropertyInfo[]? GetTaskParameters() => _props; public bool Initialize(string taskName, IDictionary<string, TaskPropertyInfo> parameterGroup, string taskBody, IBuildEngine taskFactoryLoggingHost) { _props = parameterGroup.Values.ToArray(); return true; } private class DummyTask : IGeneratedTask { public IBuildEngine? BuildEngine { get; set; } public ITaskHost? HostObject { get; set; } public bool Execute() => true; public object GetPropertyValue(TaskPropertyInfo property) => null!; public void SetPropertyValue(TaskPropertyInfo property, object value) { } } } }
-1
dotnet/roslyn
55,419
Make vsix's compatible with vs 2022
Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
dibarbet
2021-08-04T23:36:41Z
2021-08-06T17:54:08Z
082df2aaf6a73277fc27f9d7a5a8d18ee45d7f8b
e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028
Make vsix's compatible with vs 2022. Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
./src/EditorFeatures/CSharpTest/SignatureHelp/ConstructorInitializerSignatureHelpProviderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.SignatureHelp; using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SignatureHelp { public class ConstructorInitializerSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests { internal override Type GetSignatureHelpProviderType() => typeof(ConstructorInitializerSignatureHelpProvider); #region "Regular tests" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithoutParameters() { var markup = @" class BaseClass { public BaseClass() { } } class Derived : BaseClass { public Derived() [|: base($$|]) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass()", string.Empty, null, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithoutParametersMethodXmlComments() { var markup = @" class BaseClass { /// <summary>Summary for BaseClass</summary> public BaseClass() { } } class Derived : BaseClass { public Derived() [|: base($$|]) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass()", "Summary for BaseClass", null, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithParametersOn1() { var markup = @" class BaseClass { public BaseClass(int a, int b) { } } class Derived : BaseClass { public Derived() [|: base($$2, 3|]) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithParametersXmlCommentsOn1() { var markup = @" class BaseClass { /// <summary>Summary for BaseClass</summary> /// <param name=""a"">Param a</param> /// <param name=""b"">Param b</param> public BaseClass(int a, int b) { } } class Derived : BaseClass { public Derived() [|: base($$2, 3|]) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass(int a, int b)", "Summary for BaseClass", "Param a", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithParametersOn2() { var markup = @" class BaseClass { /// <summary>Summary for BaseClass</summary> /// <param name=""a"">Param a</param> /// <param name=""b"">Param b</param> public BaseClass(int a, int b) { } } class Derived : BaseClass { public Derived() [|: base(2, $$3|]) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass(int a, int b)", "Summary for BaseClass", "Param b", currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithParametersXmlComentsOn2() { var markup = @" class BaseClass { /// <summary>Summary for BaseClass</summary> /// <param name=""a"">Param a</param> /// <param name=""b"">Param b</param> public BaseClass(int a, int b) { } } class Derived : BaseClass { public Derived() [|: base(2, $$3|]) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass(int a, int b)", "Summary for BaseClass", "Param b", currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } [WorkItem(2579, "https://github.com/dotnet/roslyn/issues/2579")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestThisInvocation() { var markup = @" class Goo { public Goo(int a, int b) { } public Goo() [|: this(2, $$3|]) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("Goo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1) }; await TestAsync(markup, expectedOrderedItems); } [WorkItem(2579, "https://github.com/dotnet/roslyn/issues/2579")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestThisInvocationWithNonEmptyArgumentList() { var markup = @" class Foo { public Foo(int a, int b) [|: this($$|]) { } public Foo() { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("Foo()", string.Empty, null, currentParameterIndex: 0), }; await TestAsync(markup, expectedOrderedItems); } [WorkItem(2579, "https://github.com/dotnet/roslyn/issues/2579")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithoutClosingParen() { var markup = @" class Goo { public Goo(int a, int b) { } public Goo() [|: this(2, $$ |]}"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("Goo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1) }; await TestAsync(markup, expectedOrderedItems); } [WorkItem(2579, "https://github.com/dotnet/roslyn/issues/2579")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestThisInvocationWithoutClosingParenWithNonEmptyArgumentList() { var markup = @" class Foo { public Foo() { } public Foo(int a, int b) [|: this($$ |]}"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("Foo()", string.Empty, null, currentParameterIndex: 0), }; await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] [WorkItem(25830, "https://github.com/dotnet/roslyn/issues/25830")] public async Task PickCorrectOverload_PickInt() { var markup = @" class D { D() [|: this(i: 1$$|]) { } D(D filtered) => throw null; D(string i) => throw null; D(int i) => throw null; }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("D(int i)", currentParameterIndex: 0, isSelected: true), new SignatureHelpTestItem("D(string i)", currentParameterIndex: 0), }; await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] [WorkItem(25830, "https://github.com/dotnet/roslyn/issues/25830")] public async Task PickCorrectOverload_PickString() { var markup = @" class D { D() [|: this(i: null$$|]) { } D(D filtered) => throw null; D(string i) => throw null; D(int i) => throw null; }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("D(int i)", currentParameterIndex: 0), new SignatureHelpTestItem("D(string i)", currentParameterIndex: 0, isSelected: true), }; await TestAsync(markup, expectedOrderedItems); } #endregion #region "Current Parameter Name" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestCurrentParameterName() { var markup = @" class Goo { public Goo(int a, int b) { } public Goo() : this(b: 2, a: $$ }"; await VerifyCurrentParameterNameAsync(markup, "a"); } #endregion #region "Trigger tests" [WorkItem(2579, "https://github.com/dotnet/roslyn/issues/2579")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationOnTriggerParens() { var markup = @" class Goo { public Goo(int a) { } public Goo() : this($$ }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("Goo(int a)", string.Empty, string.Empty, currentParameterIndex: 0) }; await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [WorkItem(2579, "https://github.com/dotnet/roslyn/issues/2579")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationOnTriggerParensWithNonEmptyArgumentList() { var markup = @" class Foo { public Foo(int a) : this($$ public Foo() { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("Foo()", string.Empty, null, currentParameterIndex: 0), }; await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [WorkItem(2579, "https://github.com/dotnet/roslyn/issues/2579")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationOnTriggerComma() { var markup = @" class Goo { public Goo(int a, int b) { } public Goo() : this(2,$$ }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("Goo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1) }; await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [WorkItem(2579, "https://github.com/dotnet/roslyn/issues/2579")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationOnTriggerCommaWithNonEmptyArgumentList() { var markup = @" class Foo { public Foo(int a, int b) : this($$ public Foo() { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("Foo()", string.Empty, null, currentParameterIndex: 0), }; await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestNoInvocationOnSpace() { var markup = @" class Goo { public Goo(int a, int b) { } public Goo() : this(2, $$ }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestTriggerCharacters() { char[] expectedCharacters = { ',', '(' }; char[] unexpectedCharacters = { ' ', '[', '<' }; VerifyTriggerCharacters(expectedCharacters, unexpectedCharacters); } #endregion #region "EditorBrowsable tests" [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_ConstructorInitializer_BrowsableStateAlways() { var markup = @" class DerivedClass : BaseClass { public DerivedClass() : base($$ }"; var referencedCode = @" public class BaseClass { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public BaseClass(int x) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_ConstructorInitializer_BrowsableStateNever() { var markup = @" class DerivedClass : BaseClass { public DerivedClass() : base($$ }"; var referencedCode = @" public class BaseClass { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public BaseClass(int x) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_ConstructorInitializer_BrowsableStateAdvanced() { var markup = @" class DerivedClass : BaseClass { public DerivedClass() : base($$ }"; var referencedCode = @" public class BaseClass { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public BaseClass(int x) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_ConstructorInitializer_BrowsableStateMixed() { var markup = @" class DerivedClass : BaseClass { public DerivedClass() : base($$ }"; var referencedCode = @" public class BaseClass { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public BaseClass(int x) { } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public BaseClass(int x, int y) { } }"; var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>(); expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("BaseClass(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>(); expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("BaseClass(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("BaseClass(int x, int y)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference, expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } #endregion [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task FieldUnavailableInOneLinkedFile() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if GOO class Secret { public Secret(int secret) { } } #endif class SuperSecret : Secret { public SuperSecret(int secret) : base($$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = new SignatureHelpTestItem($"Secret(int secret)\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", currentParameterIndex: 0); await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task ExcludeFilesWithInactiveRegions() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO,BAR""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if GOO class Secret { public Secret(int secret) { } } #endif #if BAR class SuperSecret : Secret { public SuperSecret(int secret) : base($$ } #endif } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument"" /> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = new SignatureHelpTestItem($"Secret(int secret)\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", currentParameterIndex: 0); await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false); } [WorkItem(1067933, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067933")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InvokedWithNoToken() { var markup = @" // goo($$"; await TestAsync(markup); } [WorkItem(1082601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1082601")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithBadParameterList() { var markup = @" class BaseClass { public BaseClass() { } } class Derived : BaseClass { public Derived() [|: base{$$|]) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TypingTupleDoesNotDismiss1() { var markup = @" class D { public D(object o) {} } class C : D { public C() [|: base(($$) |]{} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("D(object o)", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TypingTupleDoesNotDismiss2() { var markup = @" class D { public D(object o) {} } class C : D { public C() [|: base((1,$$) |]{} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("D(object o)", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TypingTupleDoesNotDismiss3() { var markup = @" class D { public D(object o) {} } class C : D { public C() [|: base((1, ($$) |]{} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("D(object o)", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TypingTupleDoesNotDismiss4() { var markup = @" class D { public D(object o) {} } class C : D { public C() [|: base((1, (2,$$) |]{} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("D(object o)", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: 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.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.SignatureHelp; using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SignatureHelp { public class ConstructorInitializerSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests { internal override Type GetSignatureHelpProviderType() => typeof(ConstructorInitializerSignatureHelpProvider); #region "Regular tests" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithoutParameters() { var markup = @" class BaseClass { public BaseClass() { } } class Derived : BaseClass { public Derived() [|: base($$|]) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass()", string.Empty, null, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithoutParametersMethodXmlComments() { var markup = @" class BaseClass { /// <summary>Summary for BaseClass</summary> public BaseClass() { } } class Derived : BaseClass { public Derived() [|: base($$|]) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass()", "Summary for BaseClass", null, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithParametersOn1() { var markup = @" class BaseClass { public BaseClass(int a, int b) { } } class Derived : BaseClass { public Derived() [|: base($$2, 3|]) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithParametersXmlCommentsOn1() { var markup = @" class BaseClass { /// <summary>Summary for BaseClass</summary> /// <param name=""a"">Param a</param> /// <param name=""b"">Param b</param> public BaseClass(int a, int b) { } } class Derived : BaseClass { public Derived() [|: base($$2, 3|]) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass(int a, int b)", "Summary for BaseClass", "Param a", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithParametersOn2() { var markup = @" class BaseClass { /// <summary>Summary for BaseClass</summary> /// <param name=""a"">Param a</param> /// <param name=""b"">Param b</param> public BaseClass(int a, int b) { } } class Derived : BaseClass { public Derived() [|: base(2, $$3|]) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass(int a, int b)", "Summary for BaseClass", "Param b", currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithParametersXmlComentsOn2() { var markup = @" class BaseClass { /// <summary>Summary for BaseClass</summary> /// <param name=""a"">Param a</param> /// <param name=""b"">Param b</param> public BaseClass(int a, int b) { } } class Derived : BaseClass { public Derived() [|: base(2, $$3|]) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass(int a, int b)", "Summary for BaseClass", "Param b", currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } [WorkItem(2579, "https://github.com/dotnet/roslyn/issues/2579")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestThisInvocation() { var markup = @" class Goo { public Goo(int a, int b) { } public Goo() [|: this(2, $$3|]) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("Goo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1) }; await TestAsync(markup, expectedOrderedItems); } [WorkItem(2579, "https://github.com/dotnet/roslyn/issues/2579")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestThisInvocationWithNonEmptyArgumentList() { var markup = @" class Foo { public Foo(int a, int b) [|: this($$|]) { } public Foo() { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("Foo()", string.Empty, null, currentParameterIndex: 0), }; await TestAsync(markup, expectedOrderedItems); } [WorkItem(2579, "https://github.com/dotnet/roslyn/issues/2579")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithoutClosingParen() { var markup = @" class Goo { public Goo(int a, int b) { } public Goo() [|: this(2, $$ |]}"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("Goo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1) }; await TestAsync(markup, expectedOrderedItems); } [WorkItem(2579, "https://github.com/dotnet/roslyn/issues/2579")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestThisInvocationWithoutClosingParenWithNonEmptyArgumentList() { var markup = @" class Foo { public Foo() { } public Foo(int a, int b) [|: this($$ |]}"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("Foo()", string.Empty, null, currentParameterIndex: 0), }; await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] [WorkItem(25830, "https://github.com/dotnet/roslyn/issues/25830")] public async Task PickCorrectOverload_PickInt() { var markup = @" class D { D() [|: this(i: 1$$|]) { } D(D filtered) => throw null; D(string i) => throw null; D(int i) => throw null; }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("D(int i)", currentParameterIndex: 0, isSelected: true), new SignatureHelpTestItem("D(string i)", currentParameterIndex: 0), }; await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] [WorkItem(25830, "https://github.com/dotnet/roslyn/issues/25830")] public async Task PickCorrectOverload_PickString() { var markup = @" class D { D() [|: this(i: null$$|]) { } D(D filtered) => throw null; D(string i) => throw null; D(int i) => throw null; }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("D(int i)", currentParameterIndex: 0), new SignatureHelpTestItem("D(string i)", currentParameterIndex: 0, isSelected: true), }; await TestAsync(markup, expectedOrderedItems); } #endregion #region "Current Parameter Name" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestCurrentParameterName() { var markup = @" class Goo { public Goo(int a, int b) { } public Goo() : this(b: 2, a: $$ }"; await VerifyCurrentParameterNameAsync(markup, "a"); } #endregion #region "Trigger tests" [WorkItem(2579, "https://github.com/dotnet/roslyn/issues/2579")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationOnTriggerParens() { var markup = @" class Goo { public Goo(int a) { } public Goo() : this($$ }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("Goo(int a)", string.Empty, string.Empty, currentParameterIndex: 0) }; await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [WorkItem(2579, "https://github.com/dotnet/roslyn/issues/2579")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationOnTriggerParensWithNonEmptyArgumentList() { var markup = @" class Foo { public Foo(int a) : this($$ public Foo() { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("Foo()", string.Empty, null, currentParameterIndex: 0), }; await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [WorkItem(2579, "https://github.com/dotnet/roslyn/issues/2579")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationOnTriggerComma() { var markup = @" class Goo { public Goo(int a, int b) { } public Goo() : this(2,$$ }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("Goo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1) }; await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [WorkItem(2579, "https://github.com/dotnet/roslyn/issues/2579")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationOnTriggerCommaWithNonEmptyArgumentList() { var markup = @" class Foo { public Foo(int a, int b) : this($$ public Foo() { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("Foo()", string.Empty, null, currentParameterIndex: 0), }; await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestNoInvocationOnSpace() { var markup = @" class Goo { public Goo(int a, int b) { } public Goo() : this(2, $$ }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestTriggerCharacters() { char[] expectedCharacters = { ',', '(' }; char[] unexpectedCharacters = { ' ', '[', '<' }; VerifyTriggerCharacters(expectedCharacters, unexpectedCharacters); } #endregion #region "EditorBrowsable tests" [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_ConstructorInitializer_BrowsableStateAlways() { var markup = @" class DerivedClass : BaseClass { public DerivedClass() : base($$ }"; var referencedCode = @" public class BaseClass { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public BaseClass(int x) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_ConstructorInitializer_BrowsableStateNever() { var markup = @" class DerivedClass : BaseClass { public DerivedClass() : base($$ }"; var referencedCode = @" public class BaseClass { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public BaseClass(int x) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_ConstructorInitializer_BrowsableStateAdvanced() { var markup = @" class DerivedClass : BaseClass { public DerivedClass() : base($$ }"; var referencedCode = @" public class BaseClass { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public BaseClass(int x) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_ConstructorInitializer_BrowsableStateMixed() { var markup = @" class DerivedClass : BaseClass { public DerivedClass() : base($$ }"; var referencedCode = @" public class BaseClass { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public BaseClass(int x) { } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public BaseClass(int x, int y) { } }"; var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>(); expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("BaseClass(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>(); expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("BaseClass(int x)", string.Empty, string.Empty, currentParameterIndex: 0)); expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("BaseClass(int x, int y)", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference, expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } #endregion [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task FieldUnavailableInOneLinkedFile() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if GOO class Secret { public Secret(int secret) { } } #endif class SuperSecret : Secret { public SuperSecret(int secret) : base($$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = new SignatureHelpTestItem($"Secret(int secret)\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", currentParameterIndex: 0); await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task ExcludeFilesWithInactiveRegions() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO,BAR""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if GOO class Secret { public Secret(int secret) { } } #endif #if BAR class SuperSecret : Secret { public SuperSecret(int secret) : base($$ } #endif } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument"" /> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = new SignatureHelpTestItem($"Secret(int secret)\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", currentParameterIndex: 0); await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false); } [WorkItem(1067933, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067933")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InvokedWithNoToken() { var markup = @" // goo($$"; await TestAsync(markup); } [WorkItem(1082601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1082601")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestInvocationWithBadParameterList() { var markup = @" class BaseClass { public BaseClass() { } } class Derived : BaseClass { public Derived() [|: base{$$|]) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TypingTupleDoesNotDismiss1() { var markup = @" class D { public D(object o) {} } class C : D { public C() [|: base(($$) |]{} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("D(object o)", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TypingTupleDoesNotDismiss2() { var markup = @" class D { public D(object o) {} } class C : D { public C() [|: base((1,$$) |]{} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("D(object o)", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TypingTupleDoesNotDismiss3() { var markup = @" class D { public D(object o) {} } class C : D { public C() [|: base((1, ($$) |]{} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("D(object o)", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TypingTupleDoesNotDismiss4() { var markup = @" class D { public D(object o) {} } class C : D { public C() [|: base((1, (2,$$) |]{} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("D(object o)", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } } }
-1
dotnet/roslyn
55,419
Make vsix's compatible with vs 2022
Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
dibarbet
2021-08-04T23:36:41Z
2021-08-06T17:54:08Z
082df2aaf6a73277fc27f9d7a5a8d18ee45d7f8b
e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028
Make vsix's compatible with vs 2022. Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
./src/Scripting/CSharp/Hosting/ObjectFormatter/CSharpTypeNameFormatter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.Scripting.Hosting; namespace Microsoft.CodeAnalysis.CSharp.Scripting.Hosting { internal class CSharpTypeNameFormatter : CommonTypeNameFormatter { protected override CommonPrimitiveFormatter PrimitiveFormatter { get; } public CSharpTypeNameFormatter(CommonPrimitiveFormatter primitiveFormatter) { PrimitiveFormatter = primitiveFormatter; } protected override string GenericParameterOpening => "<"; protected override string GenericParameterClosing => ">"; protected override string ArrayOpening => "["; protected override string ArrayClosing => "]"; protected override string GetPrimitiveTypeName(SpecialType type) { switch (type) { case SpecialType.System_Boolean: return "bool"; case SpecialType.System_Byte: return "byte"; case SpecialType.System_Char: return "char"; case SpecialType.System_Decimal: return "decimal"; case SpecialType.System_Double: return "double"; case SpecialType.System_Int16: return "short"; case SpecialType.System_Int32: return "int"; case SpecialType.System_Int64: return "long"; case SpecialType.System_SByte: return "sbyte"; case SpecialType.System_Single: return "float"; case SpecialType.System_String: return "string"; case SpecialType.System_UInt16: return "ushort"; case SpecialType.System_UInt32: return "uint"; case SpecialType.System_UInt64: return "ulong"; case SpecialType.System_Object: return "object"; default: return null; } } public override string FormatTypeName(Type type, CommonTypeNameFormatterOptions options) { string stateMachineName; if (GeneratedNames.TryParseSourceMethodNameFromGeneratedName(type.Name, GeneratedNameKind.StateMachineType, out stateMachineName)) { return stateMachineName; } return base.FormatTypeName(type, options); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.Scripting.Hosting; namespace Microsoft.CodeAnalysis.CSharp.Scripting.Hosting { internal class CSharpTypeNameFormatter : CommonTypeNameFormatter { protected override CommonPrimitiveFormatter PrimitiveFormatter { get; } public CSharpTypeNameFormatter(CommonPrimitiveFormatter primitiveFormatter) { PrimitiveFormatter = primitiveFormatter; } protected override string GenericParameterOpening => "<"; protected override string GenericParameterClosing => ">"; protected override string ArrayOpening => "["; protected override string ArrayClosing => "]"; protected override string GetPrimitiveTypeName(SpecialType type) { switch (type) { case SpecialType.System_Boolean: return "bool"; case SpecialType.System_Byte: return "byte"; case SpecialType.System_Char: return "char"; case SpecialType.System_Decimal: return "decimal"; case SpecialType.System_Double: return "double"; case SpecialType.System_Int16: return "short"; case SpecialType.System_Int32: return "int"; case SpecialType.System_Int64: return "long"; case SpecialType.System_SByte: return "sbyte"; case SpecialType.System_Single: return "float"; case SpecialType.System_String: return "string"; case SpecialType.System_UInt16: return "ushort"; case SpecialType.System_UInt32: return "uint"; case SpecialType.System_UInt64: return "ulong"; case SpecialType.System_Object: return "object"; default: return null; } } public override string FormatTypeName(Type type, CommonTypeNameFormatterOptions options) { string stateMachineName; if (GeneratedNames.TryParseSourceMethodNameFromGeneratedName(type.Name, GeneratedNameKind.StateMachineType, out stateMachineName)) { return stateMachineName; } return base.FormatTypeName(type, options); } } }
-1
dotnet/roslyn
55,419
Make vsix's compatible with vs 2022
Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
dibarbet
2021-08-04T23:36:41Z
2021-08-06T17:54:08Z
082df2aaf6a73277fc27f9d7a5a8d18ee45d7f8b
e1585f823c2ff9e4e7d22a5cc285d5ccf4b1b028
Make vsix's compatible with vs 2022. Currently attempting to install any VSIX roslyn vsix built in artifacts will only allow installation into vs 2019. VSIX install is a scenario sometimes used for sharing changes with partner teams for validation. @CyrusNajmabadi and @LinglingTong have both encountered this problem. Insertions do not use the vsix installer and are handled separately, so this is not a problem there. The changes in this PR (per guidance [here](https://docs.microsoft.com/en-us/visualstudio/extensibility/migration/update-visual-studio-extension?view=vs-2022#add-a-visual-studio-2022-target)) make it so our VSIXs are installable into VS 2022. Note that they will not be installable in 2019, but VS 2022 is already a requirement to appropriately build and deploy main anyway. I verified that after this change I can double click install the vsix into 2022 and that my changes were reflected once installed. Test insertion - https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342463 The RPS regressions are the exact same ones we're seeing in main (see [this insertion](https://dev.azure.com/devdiv/DevDiv/_git/VS/pullrequest/342430)), so counting that as passing
./src/Features/VisualBasic/Portable/Structure/Providers/EnumMemberDeclarationStructureProvider.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis.[Shared].Collections Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Structure Friend Class EnumMemberDeclarationStructureProvider Inherits AbstractSyntaxNodeStructureProvider(Of EnumMemberDeclarationSyntax) Protected Overrides Sub CollectBlockSpans(previousToken As SyntaxToken, enumMemberDeclaration As EnumMemberDeclarationSyntax, ByRef spans As TemporaryArray(Of BlockSpan), optionProvider As BlockStructureOptionProvider, cancellationToken As CancellationToken) CollectCommentsRegions(enumMemberDeclaration, spans, optionProvider) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis.[Shared].Collections Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Structure Friend Class EnumMemberDeclarationStructureProvider Inherits AbstractSyntaxNodeStructureProvider(Of EnumMemberDeclarationSyntax) Protected Overrides Sub CollectBlockSpans(previousToken As SyntaxToken, enumMemberDeclaration As EnumMemberDeclarationSyntax, ByRef spans As TemporaryArray(Of BlockSpan), optionProvider As BlockStructureOptionProvider, cancellationToken As CancellationToken) CollectCommentsRegions(enumMemberDeclaration, spans, optionProvider) End Sub End Class End Namespace
-1
dotnet/roslyn
55,409
Use FixedSize API
tmat
2021-08-04T19:30:40Z
2021-08-04T21:53:46Z
e0112742bff208dd0546de45e36f7b52058a45a3
c90bf0ec986010051662c8e1fbc872c2fd86bc4e
Use FixedSize API.
./src/Features/CSharp/Portable/EditAndContinue/CSharpEditAndContinueAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Differencing; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue { internal sealed class CSharpEditAndContinueAnalyzer : AbstractEditAndContinueAnalyzer { [ExportLanguageServiceFactory(typeof(IEditAndContinueAnalyzer), LanguageNames.CSharp), Shared] internal sealed class Factory : ILanguageServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public Factory() { } public ILanguageService CreateLanguageService(HostLanguageServices languageServices) { return new CSharpEditAndContinueAnalyzer(testFaultInjector: null); } } // Public for testing purposes public CSharpEditAndContinueAnalyzer(Action<SyntaxNode>? testFaultInjector = null) : base(testFaultInjector) { } #region Syntax Analysis private enum BlockPart { OpenBrace = DefaultStatementPart, CloseBrace = 1, } private enum ForEachPart { ForEach = DefaultStatementPart, VariableDeclaration = 1, In = 2, Expression = 3, } private enum SwitchExpressionPart { WholeExpression = DefaultStatementPart, // An active statement that covers IL generated for the decision tree: // <governing-expression> [|switch { <arm>, ..., <arm> }|] // This active statement is never a leaf active statement (does not correspond to a breakpoint span). SwitchBody = 1, } /// <returns> /// <see cref="BaseMethodDeclarationSyntax"/> for methods, operators, constructors, destructors and accessors. /// <see cref="VariableDeclaratorSyntax"/> for field initializers. /// <see cref="PropertyDeclarationSyntax"/> for property initializers and expression bodies. /// <see cref="IndexerDeclarationSyntax"/> for indexer expression bodies. /// <see cref="ArrowExpressionClauseSyntax"/> for getter of an expression-bodied property/indexer. /// </returns> internal override bool TryFindMemberDeclaration(SyntaxNode? root, SyntaxNode node, out OneOrMany<SyntaxNode> declarations) { var current = node; while (current != null && current != root) { switch (current.Kind()) { case SyntaxKind.MethodDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: declarations = new(current); return true; case SyntaxKind.PropertyDeclaration: // int P { get; } = [|initializer|]; RoslynDebug.Assert(((PropertyDeclarationSyntax)current).Initializer != null); declarations = new(current); return true; case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: // Active statements encompassing modifiers or type correspond to the first initialized field. // [|public static int F = 1|], G = 2; declarations = new(((BaseFieldDeclarationSyntax)current).Declaration.Variables.First()); return true; case SyntaxKind.VariableDeclarator: // public static int F = 1, [|G = 2|]; RoslynDebug.Assert(current.Parent.IsKind(SyntaxKind.VariableDeclaration)); switch (current.Parent.Parent!.Kind()) { case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: declarations = new(current); return true; } current = current.Parent; break; case SyntaxKind.ArrowExpressionClause: // represents getter symbol declaration node of a property/indexer with expression body if (current.Parent.IsKind(SyntaxKind.PropertyDeclaration, SyntaxKind.IndexerDeclaration)) { declarations = new(current); return true; } break; } current = current.Parent; } declarations = default; return false; } /// <returns> /// Given a node representing a declaration or a top-level match node returns: /// - <see cref="BlockSyntax"/> for method-like member declarations with block bodies (methods, operators, constructors, destructors, accessors). /// - <see cref="ExpressionSyntax"/> for variable declarators of fields, properties with an initializer expression, or /// for method-like member declarations with expression bodies (methods, properties, indexers, operators) /// - <see cref="CompilationUnitSyntax"/> for top level statements /// /// A null reference otherwise. /// </returns> internal override SyntaxNode? TryGetDeclarationBody(SyntaxNode node) { if (node.IsKind(SyntaxKind.VariableDeclarator, out VariableDeclaratorSyntax? variableDeclarator)) { return variableDeclarator.Initializer?.Value; } if (node is CompilationUnitSyntax unit && unit.ContainsTopLevelStatements()) { // For top level statements, where there is no syntax node to represent the entire body of the synthesized // main method we just use the compilation unit itself return node; } return SyntaxUtilities.TryGetMethodDeclarationBody(node); } internal override bool IsDeclarationWithSharedBody(SyntaxNode declaration) => false; protected override ImmutableArray<ISymbol> GetCapturedVariables(SemanticModel model, SyntaxNode memberBody) { if (memberBody is CompilationUnitSyntax unit && unit.ContainsTopLevelStatements()) { return model.AnalyzeDataFlow(((GlobalStatementSyntax)unit.Members[0]).Statement, unit.Members.OfType<GlobalStatementSyntax>().Last().Statement)!.Captured; } Debug.Assert(memberBody.IsKind(SyntaxKind.Block) || memberBody is ExpressionSyntax); return model.AnalyzeDataFlow(memberBody).Captured; } protected override bool AreFixedSizeBufferSizesEqual(IFieldSymbol oldField, IFieldSymbol newField, CancellationToken cancellationToken) { // TODO: replace with symbolic API once available (https://github.com/dotnet/roslyn/issues/54799) Debug.Assert(oldField.IsFixedSizeBuffer); Debug.Assert(oldField.DeclaringSyntaxReferences.Length == 1); Debug.Assert(newField.IsFixedSizeBuffer); Debug.Assert(newField.DeclaringSyntaxReferences.Length == 1); var oldSyntax = (VariableDeclaratorSyntax)oldField.DeclaringSyntaxReferences.Single().GetSyntax(cancellationToken); var newSyntax = (VariableDeclaratorSyntax)newField.DeclaringSyntaxReferences.Single().GetSyntax(cancellationToken); Debug.Assert(oldSyntax.ArgumentList != null); Debug.Assert(newSyntax.ArgumentList != null); return AreEquivalent(oldSyntax.ArgumentList, newSyntax.ArgumentList); } protected override bool AreHandledEventsEqual(IMethodSymbol oldMethod, IMethodSymbol newMethod) => true; internal override bool HasParameterClosureScope(ISymbol member) { // in instance constructor parameters are lifted to a closure different from method body return (member as IMethodSymbol)?.MethodKind == MethodKind.Constructor; } protected override IEnumerable<SyntaxNode> GetVariableUseSites(IEnumerable<SyntaxNode> roots, ISymbol localOrParameter, SemanticModel model, CancellationToken cancellationToken) { Debug.Assert(localOrParameter is IParameterSymbol || localOrParameter is ILocalSymbol || localOrParameter is IRangeVariableSymbol); // not supported (it's non trivial to find all places where "this" is used): Debug.Assert(!localOrParameter.IsThisParameter()); return from root in roots from node in root.DescendantNodesAndSelf() where node.IsKind(SyntaxKind.IdentifierName) let nameSyntax = (IdentifierNameSyntax)node where (string?)nameSyntax.Identifier.Value == localOrParameter.Name && (model.GetSymbolInfo(nameSyntax, cancellationToken).Symbol?.Equals(localOrParameter) ?? false) select node; } /// <returns> /// If <paramref name="node"/> is a method, accessor, operator, destructor, or constructor without an initializer, /// tokens of its block body, or tokens of the expression body. /// /// If <paramref name="node"/> is an indexer declaration the tokens of its expression body. /// /// If <paramref name="node"/> is a property declaration the tokens of its expression body or initializer. /// /// If <paramref name="node"/> is a constructor with an initializer, /// tokens of the initializer concatenated with tokens of the constructor body. /// /// If <paramref name="node"/> is a variable declarator of a field with an initializer, /// subset of the tokens of the field declaration depending on which variable declarator it is. /// /// Null reference otherwise. /// </returns> internal override IEnumerable<SyntaxToken>? TryGetActiveTokens(SyntaxNode node) { if (node.IsKind(SyntaxKind.VariableDeclarator)) { // TODO: The logic is similar to BreakpointSpans.TryCreateSpanForVariableDeclaration. Can we abstract it? var declarator = node; var fieldDeclaration = (BaseFieldDeclarationSyntax)declarator.Parent!.Parent!; var variableDeclaration = fieldDeclaration.Declaration; if (fieldDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword)) { return null; } if (variableDeclaration.Variables.Count == 1) { if (variableDeclaration.Variables[0].Initializer == null) { return null; } return fieldDeclaration.Modifiers.Concat(variableDeclaration.DescendantTokens()).Concat(fieldDeclaration.SemicolonToken); } if (declarator == variableDeclaration.Variables[0]) { return fieldDeclaration.Modifiers.Concat(variableDeclaration.Type.DescendantTokens()).Concat(node.DescendantTokens()); } return declarator.DescendantTokens(); } if (node is PropertyDeclarationSyntax { ExpressionBody: var propertyExpressionBody and not null }) { return propertyExpressionBody.Expression.DescendantTokens(); } if (node is IndexerDeclarationSyntax { ExpressionBody: var indexerExpressionBody and not null }) { return indexerExpressionBody.Expression.DescendantTokens(); } var bodyTokens = SyntaxUtilities.TryGetMethodDeclarationBody(node)?.DescendantTokens(); if (node.IsKind(SyntaxKind.ConstructorDeclaration, out ConstructorDeclarationSyntax? ctor)) { if (ctor.Initializer != null) { bodyTokens = ctor.Initializer.DescendantTokens().Concat(bodyTokens ?? Enumerable.Empty<SyntaxToken>()); } } return bodyTokens; } internal override (TextSpan envelope, TextSpan hole) GetActiveSpanEnvelope(SyntaxNode declaration) => (BreakpointSpans.GetEnvelope(declaration), default); protected override SyntaxNode GetEncompassingAncestorImpl(SyntaxNode bodyOrMatchRoot) { // Constructor may contain active nodes outside of its body (constructor initializer), // but within the body of the member declaration (the parent). if (bodyOrMatchRoot.Parent.IsKind(SyntaxKind.ConstructorDeclaration)) { return bodyOrMatchRoot.Parent; } // Field initializer match root -- an active statement may include the modifiers // and type specification of the field declaration. if (bodyOrMatchRoot.IsKind(SyntaxKind.EqualsValueClause) && bodyOrMatchRoot.Parent.IsKind(SyntaxKind.VariableDeclarator) && bodyOrMatchRoot.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration)) { return bodyOrMatchRoot.Parent.Parent; } // Field initializer body -- an active statement may include the modifiers // and type specification of the field declaration. if (bodyOrMatchRoot.Parent.IsKind(SyntaxKind.EqualsValueClause) && bodyOrMatchRoot.Parent.Parent.IsKind(SyntaxKind.VariableDeclarator) && bodyOrMatchRoot.Parent.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration)) { return bodyOrMatchRoot.Parent.Parent.Parent; } // otherwise all active statements are covered by the body/match root itself: return bodyOrMatchRoot; } protected override SyntaxNode FindStatementAndPartner(SyntaxNode declarationBody, TextSpan span, SyntaxNode? partnerDeclarationBody, out SyntaxNode? partner, out int statementPart) { var position = span.Start; SyntaxUtilities.AssertIsBody(declarationBody, allowLambda: false); if (position < declarationBody.SpanStart) { // Only constructors and the field initializers may have an [|active statement|] starting outside of the <<body>>. // Constructor: [|public C()|] <<{ }>> // Constructor initializer: public C() : [|base(expr)|] <<{ }>> // Constructor initializer with lambda: public C() : base(() => { [|...|] }) <<{ }>> // Field initializers: [|public int a = <<expr>>|], [|b = <<expr>>|]; // No need to special case property initializers here, the active statement always spans the initializer expression. if (declarationBody.Parent.IsKind(SyntaxKind.ConstructorDeclaration)) { var constructor = (ConstructorDeclarationSyntax)declarationBody.Parent; var partnerConstructor = (ConstructorDeclarationSyntax?)partnerDeclarationBody?.Parent; if (constructor.Initializer == null || position < constructor.Initializer.ColonToken.SpanStart) { statementPart = DefaultStatementPart; partner = partnerConstructor; return constructor; } declarationBody = constructor.Initializer; partnerDeclarationBody = partnerConstructor?.Initializer; } } if (!declarationBody.FullSpan.Contains(position)) { // invalid position, let's find a labeled node that encompasses the body: position = declarationBody.SpanStart; } SyntaxNode node; if (partnerDeclarationBody != null) { SyntaxUtilities.FindLeafNodeAndPartner(declarationBody, position, partnerDeclarationBody, out node, out partner); } else { node = declarationBody.FindToken(position).Parent!; partner = null; } while (true) { var isBody = node == declarationBody || LambdaUtilities.IsLambdaBodyStatementOrExpression(node); if (isBody || SyntaxComparer.Statement.HasLabel(node)) { switch (node.Kind()) { case SyntaxKind.Block: statementPart = (int)GetStatementPart((BlockSyntax)node, position); return node; case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: Debug.Assert(!isBody); statementPart = (int)GetStatementPart((CommonForEachStatementSyntax)node, position); return node; case SyntaxKind.DoStatement: // The active statement of DoStatement node is the while condition, // which is lexically not the closest breakpoint span (the body is). // do { ... } [|while (condition);|] Debug.Assert(position == ((DoStatementSyntax)node).WhileKeyword.SpanStart); Debug.Assert(!isBody); goto default; case SyntaxKind.PropertyDeclaration: // The active span corresponding to a property declaration is the span corresponding to its initializer (if any), // not the span corresponding to the accessor. // int P { [|get;|] } = [|<initializer>|]; Debug.Assert(position == ((PropertyDeclarationSyntax)node).Initializer!.SpanStart); goto default; case SyntaxKind.VariableDeclaration: // VariableDeclaration ::= TypeSyntax CommaSeparatedList(VariableDeclarator) // // The compiler places sequence points after each local variable initialization. // The TypeSyntax is considered to be part of the first sequence span. Debug.Assert(!isBody); node = ((VariableDeclarationSyntax)node).Variables.First(); if (partner != null) { partner = ((VariableDeclarationSyntax)partner).Variables.First(); } statementPart = DefaultStatementPart; return node; case SyntaxKind.SwitchExpression: // An active statement that covers IL generated for the decision tree: // <governing-expression> [|switch { <arm>, ..., <arm> }|] // This active statement is never a leaf active statement (does not correspond to a breakpoint span). var switchExpression = (SwitchExpressionSyntax)node; if (position == switchExpression.SwitchKeyword.SpanStart) { Debug.Assert(span.End == switchExpression.CloseBraceToken.Span.End); statementPart = (int)SwitchExpressionPart.SwitchBody; return node; } // The switch expression itself can be (a part of) an active statement associated with the containing node // For example, when it is used as a switch arm expression like so: // <expr> switch { <pattern> [|when <expr> switch { ... }|] ... } Debug.Assert(position == switchExpression.Span.Start); if (isBody) { goto default; } // ascend to parent node: break; case SyntaxKind.SwitchExpressionArm: // An active statement may occur in the when clause and in the arm expression: // <constant-pattern> [|when <condition>|] => [|<expression>|] // The former is covered by when-clause node - it's a labeled node. // The latter isn't enclosed in a distinct labeled syntax node and thus needs to be covered // by the arm node itself. Debug.Assert(position == ((SwitchExpressionArmSyntax)node).Expression.SpanStart); Debug.Assert(!isBody); goto default; default: statementPart = DefaultStatementPart; return node; } } node = node.Parent!; if (partner != null) { partner = partner.Parent; } } } private static BlockPart GetStatementPart(BlockSyntax node, int position) => position < node.OpenBraceToken.Span.End ? BlockPart.OpenBrace : BlockPart.CloseBrace; private static TextSpan GetActiveSpan(BlockSyntax node, BlockPart part) => part switch { BlockPart.OpenBrace => node.OpenBraceToken.Span, BlockPart.CloseBrace => node.CloseBraceToken.Span, _ => throw ExceptionUtilities.UnexpectedValue(part), }; private static ForEachPart GetStatementPart(CommonForEachStatementSyntax node, int position) => position < node.OpenParenToken.SpanStart ? ForEachPart.ForEach : position < node.InKeyword.SpanStart ? ForEachPart.VariableDeclaration : position < node.Expression.SpanStart ? ForEachPart.In : ForEachPart.Expression; private static TextSpan GetActiveSpan(ForEachStatementSyntax node, ForEachPart part) => part switch { ForEachPart.ForEach => node.ForEachKeyword.Span, ForEachPart.VariableDeclaration => TextSpan.FromBounds(node.Type.SpanStart, node.Identifier.Span.End), ForEachPart.In => node.InKeyword.Span, ForEachPart.Expression => node.Expression.Span, _ => throw ExceptionUtilities.UnexpectedValue(part), }; private static TextSpan GetActiveSpan(ForEachVariableStatementSyntax node, ForEachPart part) => part switch { ForEachPart.ForEach => node.ForEachKeyword.Span, ForEachPart.VariableDeclaration => TextSpan.FromBounds(node.Variable.SpanStart, node.Variable.Span.End), ForEachPart.In => node.InKeyword.Span, ForEachPart.Expression => node.Expression.Span, _ => throw ExceptionUtilities.UnexpectedValue(part), }; private static TextSpan GetActiveSpan(SwitchExpressionSyntax node, SwitchExpressionPart part) => part switch { SwitchExpressionPart.WholeExpression => node.Span, SwitchExpressionPart.SwitchBody => TextSpan.FromBounds(node.SwitchKeyword.SpanStart, node.CloseBraceToken.Span.End), _ => throw ExceptionUtilities.UnexpectedValue(part), }; protected override bool AreEquivalent(SyntaxNode left, SyntaxNode right) => SyntaxFactory.AreEquivalent(left, right); private static bool AreEquivalentIgnoringLambdaBodies(SyntaxNode left, SyntaxNode right) { // usual case: if (SyntaxFactory.AreEquivalent(left, right)) { return true; } return LambdaUtilities.AreEquivalentIgnoringLambdaBodies(left, right); } internal override SyntaxNode FindDeclarationBodyPartner(SyntaxNode leftRoot, SyntaxNode rightRoot, SyntaxNode leftNode) => SyntaxUtilities.FindPartner(leftRoot, rightRoot, leftNode); internal override bool IsClosureScope(SyntaxNode node) => LambdaUtilities.IsClosureScope(node); protected override SyntaxNode? FindEnclosingLambdaBody(SyntaxNode? container, SyntaxNode node) { var root = GetEncompassingAncestor(container); var current = node; while (current != root && current != null) { if (LambdaUtilities.IsLambdaBodyStatementOrExpression(current, out var body)) { return body; } current = current.Parent; } return null; } protected override IEnumerable<SyntaxNode> GetLambdaBodyExpressionsAndStatements(SyntaxNode lambdaBody) => SpecializedCollections.SingletonEnumerable(lambdaBody); protected override SyntaxNode? TryGetPartnerLambdaBody(SyntaxNode oldBody, SyntaxNode newLambda) => LambdaUtilities.TryGetCorrespondingLambdaBody(oldBody, newLambda); protected override Match<SyntaxNode> ComputeTopLevelMatch(SyntaxNode oldCompilationUnit, SyntaxNode newCompilationUnit) => SyntaxComparer.TopLevel.ComputeMatch(oldCompilationUnit, newCompilationUnit); protected override Match<SyntaxNode> ComputeTopLevelDeclarationMatch(SyntaxNode oldDeclaration, SyntaxNode newDeclaration) { Contract.ThrowIfNull(oldDeclaration.Parent); Contract.ThrowIfNull(newDeclaration.Parent); var comparer = new SyntaxComparer(oldDeclaration.Parent, newDeclaration.Parent, new[] { oldDeclaration }, new[] { newDeclaration }, compareStatementSyntax: false); return comparer.ComputeMatch(oldDeclaration.Parent, newDeclaration.Parent); } protected override Match<SyntaxNode> ComputeBodyMatch(SyntaxNode oldBody, SyntaxNode newBody, IEnumerable<KeyValuePair<SyntaxNode, SyntaxNode>>? knownMatches) { SyntaxUtilities.AssertIsBody(oldBody, allowLambda: true); SyntaxUtilities.AssertIsBody(newBody, allowLambda: true); if (oldBody is ExpressionSyntax || newBody is ExpressionSyntax || (oldBody.Parent.IsKind(SyntaxKind.LocalFunctionStatement) && newBody.Parent.IsKind(SyntaxKind.LocalFunctionStatement))) { Debug.Assert(oldBody is ExpressionSyntax || oldBody is BlockSyntax); Debug.Assert(newBody is ExpressionSyntax || newBody is BlockSyntax); // The matching algorithm requires the roots to match each other. // Lambda bodies, field/property initializers, and method/property/indexer/operator expression-bodies may also be lambda expressions. // Say we have oldBody 'x => x' and newBody 'F(x => x + 1)', then // the algorithm would match 'x => x' to 'F(x => x + 1)' instead of // matching 'x => x' to 'x => x + 1'. // We use the parent node as a root: // - for field/property initializers the root is EqualsValueClause. // - for member expression-bodies the root is ArrowExpressionClauseSyntax. // - for block bodies the root is a method/operator/accessor declaration (only happens when matching expression body with a block body) // - for lambdas the root is a LambdaExpression. // - for query lambdas the root is the query clause containing the lambda (e.g. where). // - for local functions the root is LocalFunctionStatement. static SyntaxNode GetMatchingRoot(SyntaxNode body) { var parent = body.Parent!; // We could apply this change across all ArrowExpressionClause consistently not just for ones with LocalFunctionStatement parents // but it would require an essential refactoring. return parent.IsKind(SyntaxKind.ArrowExpressionClause) && parent.Parent.IsKind(SyntaxKind.LocalFunctionStatement) ? parent.Parent : parent; } var oldRoot = GetMatchingRoot(oldBody); var newRoot = GetMatchingRoot(newBody); return new SyntaxComparer(oldRoot, newRoot, GetChildNodes(oldRoot, oldBody), GetChildNodes(newRoot, newBody), compareStatementSyntax: true).ComputeMatch(oldRoot, newRoot, knownMatches); } if (oldBody.Parent.IsKind(SyntaxKind.ConstructorDeclaration)) { // We need to include constructor initializer in the match, since it may contain lambdas. // Use the constructor declaration as a root. RoslynDebug.Assert(oldBody.IsKind(SyntaxKind.Block)); RoslynDebug.Assert(newBody.IsKind(SyntaxKind.Block)); RoslynDebug.Assert(newBody.Parent.IsKind(SyntaxKind.ConstructorDeclaration)); RoslynDebug.Assert(newBody.Parent is object); return SyntaxComparer.Statement.ComputeMatch(oldBody.Parent, newBody.Parent, knownMatches); } return SyntaxComparer.Statement.ComputeMatch(oldBody, newBody, knownMatches); } private static IEnumerable<SyntaxNode> GetChildNodes(SyntaxNode root, SyntaxNode body) { if (root is LocalFunctionStatementSyntax localFunc) { // local functions have multiple children we need to process for matches, but we won't automatically // descend into them, assuming they're nested, so we override the default behaviour and return // multiple children foreach (var attributeList in localFunc.AttributeLists) { yield return attributeList; } yield return localFunc.ReturnType; if (localFunc.TypeParameterList is not null) { yield return localFunc.TypeParameterList; } yield return localFunc.ParameterList; if (localFunc.Body is not null) { yield return localFunc.Body; } else if (localFunc.ExpressionBody is not null) { // Skip the ArrowExpressionClause that is ExressionBody and just return the expression itself yield return localFunc.ExpressionBody.Expression; } } else { yield return body; } } internal override void ReportDeclarationInsertDeleteRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldNode, SyntaxNode newNode, ISymbol oldSymbol, ISymbol newSymbol, CancellationToken cancellationToken) { // Global statements have a declaring syntax reference to the compilation unit itself, which we can just ignore // for the purposes of declaration rude edits if (oldNode.IsKind(SyntaxKind.CompilationUnit) || newNode.IsKind(SyntaxKind.CompilationUnit)) { return; } // Compiler generated methods of records have a declaring syntax reference to the record declaration itself // but their explicitly implemented counterparts reference the actual member. Compiler generated properties // of records reference the parameter that names them. // // Since there is no useful "old" syntax node for these members, we can't compute declaration or body edits // using the standard tree comparison code. // // Based on this, we can detect a new explicit implementation of a record member by checking if the // declaration kind has changed. If it hasn't changed, then our standard code will handle it. if (oldNode.RawKind == newNode.RawKind) { base.ReportDeclarationInsertDeleteRudeEdits(diagnostics, oldNode, newNode, oldSymbol, newSymbol, cancellationToken); return; } // When explicitly implementing a property that is represented by a positional parameter // what looks like an edit could actually be a rude delete, or something else if (oldNode is ParameterSyntax && newNode is PropertyDeclarationSyntax property) { if (property.AccessorList!.Accessors.Count == 1) { // Explicitly implementing a property with only one accessor is a delete of the init accessor, so a rude edit. // Not implementing the get accessor would be a compile error diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ImplementRecordParameterAsReadOnly, GetDiagnosticSpan(newNode, EditKind.Delete), oldNode, new[] { property.Identifier.ToString() })); } else if (property.AccessorList.Accessors.Any(a => a.IsKind(SyntaxKind.SetAccessorDeclaration))) { // The compiler implements the properties with an init accessor so explicitly implementing // it with a set accessor is a rude accessor change edit diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ImplementRecordParameterWithSet, GetDiagnosticSpan(newNode, EditKind.Delete), oldNode, new[] { property.Identifier.ToString() })); } } else if (oldNode is RecordDeclarationSyntax && newNode is MethodDeclarationSyntax && !oldSymbol.GetParameters().Select(p => p.Name).SequenceEqual(newSymbol.GetParameters().Select(p => p.Name))) { // TODO: Remove this requirement with https://github.com/dotnet/roslyn/issues/52563 // Explicitly implemented methods must have parameter names that match the compiler generated versions // exactly otherwise symbol matching won't work for them. // We don't need to worry about parameter types, because if they were different then we wouldn't get here // as this wouldn't be the explicit implementation of a known method. // We don't need to worry about access modifiers because the symbol matching still works, and most of the // time changing access modifiers for these known methods is a compile error anyway. diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ExplicitRecordMethodParameterNamesMustMatch, GetDiagnosticSpan(newNode, EditKind.Update), oldNode, new[] { oldSymbol.ToDisplayString(SymbolDisplayFormats.NameFormat) })); } } protected override void ReportLocalFunctionsDeclarationRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> bodyMatch) { var bodyEditsForLambda = bodyMatch.GetTreeEdits(); var editMap = BuildEditMap(bodyEditsForLambda); foreach (var edit in bodyEditsForLambda.Edits) { if (HasParentEdit(editMap, edit)) { return; } var classifier = new EditClassifier(this, diagnostics, edit.OldNode, edit.NewNode, edit.Kind, bodyMatch); classifier.ClassifyEdit(); } } protected override bool TryMatchActiveStatement( SyntaxNode oldStatement, int statementPart, SyntaxNode oldBody, SyntaxNode newBody, [NotNullWhen(true)] out SyntaxNode? newStatement) { SyntaxUtilities.AssertIsBody(oldBody, allowLambda: true); SyntaxUtilities.AssertIsBody(newBody, allowLambda: true); switch (oldStatement.Kind()) { case SyntaxKind.ThisConstructorInitializer: case SyntaxKind.BaseConstructorInitializer: case SyntaxKind.ConstructorDeclaration: var newConstructor = (ConstructorDeclarationSyntax)(newBody.Parent.IsKind(SyntaxKind.ArrowExpressionClause) ? newBody.Parent.Parent : newBody.Parent)!; newStatement = (SyntaxNode?)newConstructor.Initializer ?? newConstructor; return true; default: // TODO: Consider mapping an expression body to an equivalent statement expression or return statement and vice versa. // It would benefit transformations of expression bodies to block bodies of lambdas, methods, operators and properties. // See https://github.com/dotnet/roslyn/issues/22696 // field initializer, lambda and query expressions: if (oldStatement == oldBody && !newBody.IsKind(SyntaxKind.Block)) { newStatement = newBody; return true; } newStatement = null; return false; } } #endregion #region Syntax and Semantic Utils protected override TextSpan GetGlobalStatementDiagnosticSpan(SyntaxNode node) { if (node is CompilationUnitSyntax unit) { // When deleting something from a compilation unit we just report diagnostics for the last global statement return unit.Members.OfType<GlobalStatementSyntax>().LastOrDefault()?.Span ?? default; } return GetDiagnosticSpan(node, EditKind.Delete); } protected override string LineDirectiveKeyword => "line"; protected override ushort LineDirectiveSyntaxKind => (ushort)SyntaxKind.LineDirectiveTrivia; protected override IEnumerable<SequenceEdit> GetSyntaxSequenceEdits(ImmutableArray<SyntaxNode> oldNodes, ImmutableArray<SyntaxNode> newNodes) => SyntaxComparer.GetSequenceEdits(oldNodes, newNodes); internal override SyntaxNode EmptyCompilationUnit => SyntaxFactory.CompilationUnit(); // there are no experimental features at this time. internal override bool ExperimentalFeaturesEnabled(SyntaxTree tree) => false; protected override bool StateMachineSuspensionPointKindEquals(SyntaxNode suspensionPoint1, SyntaxNode suspensionPoint2) => (suspensionPoint1 is CommonForEachStatementSyntax) ? suspensionPoint2 is CommonForEachStatementSyntax : suspensionPoint1.RawKind == suspensionPoint2.RawKind; protected override bool StatementLabelEquals(SyntaxNode node1, SyntaxNode node2) => SyntaxComparer.Statement.GetLabel(node1) == SyntaxComparer.Statement.GetLabel(node2); protected override bool TryGetEnclosingBreakpointSpan(SyntaxNode root, int position, out TextSpan span) => BreakpointSpans.TryGetClosestBreakpointSpan(root, position, out span); protected override bool TryGetActiveSpan(SyntaxNode node, int statementPart, int minLength, out TextSpan span) { switch (node.Kind()) { case SyntaxKind.Block: span = GetActiveSpan((BlockSyntax)node, (BlockPart)statementPart); return true; case SyntaxKind.ForEachStatement: span = GetActiveSpan((ForEachStatementSyntax)node, (ForEachPart)statementPart); return true; case SyntaxKind.ForEachVariableStatement: span = GetActiveSpan((ForEachVariableStatementSyntax)node, (ForEachPart)statementPart); return true; case SyntaxKind.DoStatement: // The active statement of DoStatement node is the while condition, // which is lexically not the closest breakpoint span (the body is). // do { ... } [|while (condition);|] Debug.Assert(statementPart == DefaultStatementPart); var doStatement = (DoStatementSyntax)node; return BreakpointSpans.TryGetClosestBreakpointSpan(node, doStatement.WhileKeyword.SpanStart, out span); case SyntaxKind.PropertyDeclaration: // The active span corresponding to a property declaration is the span corresponding to its initializer (if any), // not the span corresponding to the accessor. // int P { [|get;|] } = [|<initializer>|]; Debug.Assert(statementPart == DefaultStatementPart); var propertyDeclaration = (PropertyDeclarationSyntax)node; if (propertyDeclaration.Initializer != null && BreakpointSpans.TryGetClosestBreakpointSpan(node, propertyDeclaration.Initializer.SpanStart, out span)) { return true; } span = default; return false; case SyntaxKind.SwitchExpression: span = GetActiveSpan((SwitchExpressionSyntax)node, (SwitchExpressionPart)statementPart); return true; case SyntaxKind.SwitchExpressionArm: // An active statement may occur in the when clause and in the arm expression: // <constant-pattern> [|when <condition>|] => [|<expression>|] // The former is covered by when-clause node - it's a labeled node. // The latter isn't enclosed in a distinct labeled syntax node and thus needs to be covered // by the arm node itself. Debug.Assert(statementPart == DefaultStatementPart); span = ((SwitchExpressionArmSyntax)node).Expression.Span; return true; default: // make sure all nodes that use statement parts are handled above: Debug.Assert(statementPart == DefaultStatementPart); return BreakpointSpans.TryGetClosestBreakpointSpan(node, node.SpanStart, out span); } } protected override IEnumerable<(SyntaxNode statement, int statementPart)> EnumerateNearStatements(SyntaxNode statement) { var direction = +1; SyntaxNodeOrToken nodeOrToken = statement; var fieldOrPropertyModifiers = SyntaxUtilities.TryGetFieldOrPropertyModifiers(statement); while (true) { nodeOrToken = (direction < 0) ? nodeOrToken.GetPreviousSibling() : nodeOrToken.GetNextSibling(); if (nodeOrToken.RawKind == 0) { var parent = statement.Parent; if (parent == null) { yield break; } switch (parent.Kind()) { case SyntaxKind.Block: // The next sequence point hit after the last statement of a block is the closing brace: yield return (parent, (int)(direction > 0 ? BlockPart.CloseBrace : BlockPart.OpenBrace)); break; case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: // The next sequence point hit after the body is the in keyword: // [|foreach|] ([|variable-declaration|] [|in|] [|expression|]) [|<body>|] yield return (parent, (int)ForEachPart.In); break; } if (direction > 0) { nodeOrToken = statement; direction = -1; continue; } if (fieldOrPropertyModifiers.HasValue) { // We enumerated all members and none of them has an initializer. // We don't have any better place where to place the span than the initial field. // Consider: in non-partial classes we could find a single constructor. // Otherwise, it would be confusing to select one arbitrarily. yield return (statement, -1); } nodeOrToken = statement = parent; fieldOrPropertyModifiers = SyntaxUtilities.TryGetFieldOrPropertyModifiers(statement); direction = +1; yield return (nodeOrToken.AsNode()!, DefaultStatementPart); } else { var node = nodeOrToken.AsNode(); if (node == null) { continue; } if (fieldOrPropertyModifiers.HasValue) { var nodeModifiers = SyntaxUtilities.TryGetFieldOrPropertyModifiers(node); if (!nodeModifiers.HasValue || nodeModifiers.Value.Any(SyntaxKind.StaticKeyword) != fieldOrPropertyModifiers.Value.Any(SyntaxKind.StaticKeyword)) { continue; } } switch (node.Kind()) { case SyntaxKind.Block: yield return (node, (int)(direction > 0 ? BlockPart.OpenBrace : BlockPart.CloseBrace)); break; case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: yield return (node, (int)ForEachPart.ForEach); break; } yield return (node, DefaultStatementPart); } } } protected override bool AreEquivalentActiveStatements(SyntaxNode oldStatement, SyntaxNode newStatement, int statementPart) { if (oldStatement.Kind() != newStatement.Kind()) { return false; } switch (oldStatement.Kind()) { case SyntaxKind.Block: // closing brace of a using statement or a block that contains using local declarations: if (statementPart == (int)BlockPart.CloseBrace) { if (oldStatement.Parent.IsKind(SyntaxKind.UsingStatement, out UsingStatementSyntax? oldUsing)) { return newStatement.Parent.IsKind(SyntaxKind.UsingStatement, out UsingStatementSyntax? newUsing) && AreEquivalentActiveStatements(oldUsing, newUsing); } return HasEquivalentUsingDeclarations((BlockSyntax)oldStatement, (BlockSyntax)newStatement); } return true; case SyntaxKind.ConstructorDeclaration: // The call could only change if the base type of the containing class changed. return true; case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: // only check the expression, edits in the body and the variable declaration are allowed: return AreEquivalentActiveStatements((CommonForEachStatementSyntax)oldStatement, (CommonForEachStatementSyntax)newStatement); case SyntaxKind.IfStatement: // only check the condition, edits in the body are allowed: return AreEquivalentActiveStatements((IfStatementSyntax)oldStatement, (IfStatementSyntax)newStatement); case SyntaxKind.WhileStatement: // only check the condition, edits in the body are allowed: return AreEquivalentActiveStatements((WhileStatementSyntax)oldStatement, (WhileStatementSyntax)newStatement); case SyntaxKind.DoStatement: // only check the condition, edits in the body are allowed: return AreEquivalentActiveStatements((DoStatementSyntax)oldStatement, (DoStatementSyntax)newStatement); case SyntaxKind.SwitchStatement: return AreEquivalentActiveStatements((SwitchStatementSyntax)oldStatement, (SwitchStatementSyntax)newStatement); case SyntaxKind.LockStatement: return AreEquivalentActiveStatements((LockStatementSyntax)oldStatement, (LockStatementSyntax)newStatement); case SyntaxKind.UsingStatement: return AreEquivalentActiveStatements((UsingStatementSyntax)oldStatement, (UsingStatementSyntax)newStatement); // fixed and for statements don't need special handling since the active statement is a variable declaration default: return AreEquivalentIgnoringLambdaBodies(oldStatement, newStatement); } } private static bool HasEquivalentUsingDeclarations(BlockSyntax oldBlock, BlockSyntax newBlock) { var oldUsingDeclarations = oldBlock.Statements.Where(s => s is LocalDeclarationStatementSyntax l && l.UsingKeyword != default); var newUsingDeclarations = newBlock.Statements.Where(s => s is LocalDeclarationStatementSyntax l && l.UsingKeyword != default); return oldUsingDeclarations.SequenceEqual(newUsingDeclarations, AreEquivalentIgnoringLambdaBodies); } private static bool AreEquivalentActiveStatements(IfStatementSyntax oldNode, IfStatementSyntax newNode) { // only check the condition, edits in the body are allowed: return AreEquivalentIgnoringLambdaBodies(oldNode.Condition, newNode.Condition); } private static bool AreEquivalentActiveStatements(WhileStatementSyntax oldNode, WhileStatementSyntax newNode) { // only check the condition, edits in the body are allowed: return AreEquivalentIgnoringLambdaBodies(oldNode.Condition, newNode.Condition); } private static bool AreEquivalentActiveStatements(DoStatementSyntax oldNode, DoStatementSyntax newNode) { // only check the condition, edits in the body are allowed: return AreEquivalentIgnoringLambdaBodies(oldNode.Condition, newNode.Condition); } private static bool AreEquivalentActiveStatements(SwitchStatementSyntax oldNode, SwitchStatementSyntax newNode) { // only check the expression, edits in the body are allowed, unless the switch expression contains patterns: if (!AreEquivalentIgnoringLambdaBodies(oldNode.Expression, newNode.Expression)) { return false; } // Check that switch statement decision tree has not changed. var hasDecitionTree = oldNode.Sections.Any(s => s.Labels.Any(l => l is CasePatternSwitchLabelSyntax)); return !hasDecitionTree || AreEquivalentSwitchStatementDecisionTrees(oldNode, newNode); } private static bool AreEquivalentActiveStatements(LockStatementSyntax oldNode, LockStatementSyntax newNode) { // only check the expression, edits in the body are allowed: return AreEquivalentIgnoringLambdaBodies(oldNode.Expression, newNode.Expression); } private static bool AreEquivalentActiveStatements(FixedStatementSyntax oldNode, FixedStatementSyntax newNode) => AreEquivalentIgnoringLambdaBodies(oldNode.Declaration, newNode.Declaration); private static bool AreEquivalentActiveStatements(UsingStatementSyntax oldNode, UsingStatementSyntax newNode) { // only check the expression/declaration, edits in the body are allowed: return AreEquivalentIgnoringLambdaBodies( (SyntaxNode?)oldNode.Declaration ?? oldNode.Expression!, (SyntaxNode?)newNode.Declaration ?? newNode.Expression!); } private static bool AreEquivalentActiveStatements(CommonForEachStatementSyntax oldNode, CommonForEachStatementSyntax newNode) { if (oldNode.Kind() != newNode.Kind() || !AreEquivalentIgnoringLambdaBodies(oldNode.Expression, newNode.Expression)) { return false; } switch (oldNode.Kind()) { case SyntaxKind.ForEachStatement: return AreEquivalentIgnoringLambdaBodies(((ForEachStatementSyntax)oldNode).Type, ((ForEachStatementSyntax)newNode).Type); case SyntaxKind.ForEachVariableStatement: return AreEquivalentIgnoringLambdaBodies(((ForEachVariableStatementSyntax)oldNode).Variable, ((ForEachVariableStatementSyntax)newNode).Variable); default: throw ExceptionUtilities.UnexpectedValue(oldNode.Kind()); } } private static bool AreSimilarActiveStatements(CommonForEachStatementSyntax oldNode, CommonForEachStatementSyntax newNode) { List<SyntaxToken>? oldTokens = null; List<SyntaxToken>? newTokens = null; SyntaxComparer.GetLocalNames(oldNode, ref oldTokens); SyntaxComparer.GetLocalNames(newNode, ref newTokens); // A valid foreach statement declares at least one variable. RoslynDebug.Assert(oldTokens != null); RoslynDebug.Assert(newTokens != null); return DeclareSameIdentifiers(oldTokens.ToArray(), newTokens.ToArray()); } internal override bool IsInterfaceDeclaration(SyntaxNode node) => node.IsKind(SyntaxKind.InterfaceDeclaration); internal override bool IsRecordDeclaration(SyntaxNode node) => node.IsKind(SyntaxKind.RecordDeclaration, SyntaxKind.RecordStructDeclaration); internal override SyntaxNode? TryGetContainingTypeDeclaration(SyntaxNode node) => node is CompilationUnitSyntax ? null : node.Parent!.FirstAncestorOrSelf<BaseTypeDeclarationSyntax>(); internal override bool HasBackingField(SyntaxNode propertyOrIndexerDeclaration) => propertyOrIndexerDeclaration.IsKind(SyntaxKind.PropertyDeclaration, out PropertyDeclarationSyntax? propertyDecl) && SyntaxUtilities.HasBackingField(propertyDecl); internal override bool TryGetAssociatedMemberDeclaration(SyntaxNode node, [NotNullWhen(true)] out SyntaxNode? declaration) { if (node.IsKind(SyntaxKind.Parameter, SyntaxKind.TypeParameter)) { Contract.ThrowIfFalse(node.IsParentKind(SyntaxKind.ParameterList, SyntaxKind.TypeParameterList, SyntaxKind.BracketedParameterList)); declaration = node.Parent!.Parent!; return true; } if (node.Parent.IsParentKind(SyntaxKind.PropertyDeclaration, SyntaxKind.IndexerDeclaration, SyntaxKind.EventDeclaration)) { declaration = node.Parent.Parent!; return true; } declaration = null; return false; } internal override bool IsDeclarationWithInitializer(SyntaxNode declaration) => declaration is VariableDeclaratorSyntax { Initializer: not null } || declaration is PropertyDeclarationSyntax { Initializer: not null }; internal override bool IsRecordPrimaryConstructorParameter(SyntaxNode declaration) => declaration is ParameterSyntax { Parent: ParameterListSyntax { Parent: RecordDeclarationSyntax } }; private static bool IsPropertyDeclarationMatchingPrimaryConstructorParameter(SyntaxNode declaration, INamedTypeSymbol newContainingType) { if (newContainingType.IsRecord && declaration is PropertyDeclarationSyntax { Identifier: { ValueText: var name } }) { // We need to use symbol information to find the primary constructor, because it could be in another file if the type is partial foreach (var reference in newContainingType.DeclaringSyntaxReferences) { // Since users can define as many constructors as they like, going back to syntax to find the parameter list // in the record declaration is the simplest way to check if there is a matching parameter if (reference.GetSyntax() is RecordDeclarationSyntax record && record.ParameterList is not null && record.ParameterList.Parameters.Any(p => p.Identifier.ValueText.Equals(name))) { return true; } } } return false; } internal override bool IsPropertyAccessorDeclarationMatchingPrimaryConstructorParameter(SyntaxNode declaration, INamedTypeSymbol newContainingType, out bool isFirstAccessor) { isFirstAccessor = false; if (declaration is AccessorDeclarationSyntax { Parent: AccessorListSyntax { Parent: PropertyDeclarationSyntax property } list } && IsPropertyDeclarationMatchingPrimaryConstructorParameter(property, newContainingType)) { isFirstAccessor = list.Accessors[0] == declaration; return true; } return false; } internal override bool IsConstructorWithMemberInitializers(SyntaxNode constructorDeclaration) => constructorDeclaration is ConstructorDeclarationSyntax ctor && (ctor.Initializer == null || ctor.Initializer.IsKind(SyntaxKind.BaseConstructorInitializer)); internal override bool IsPartial(INamedTypeSymbol type) { var syntaxRefs = type.DeclaringSyntaxReferences; return syntaxRefs.Length > 1 || ((BaseTypeDeclarationSyntax)syntaxRefs.Single().GetSyntax()).Modifiers.Any(SyntaxKind.PartialKeyword); } protected override SyntaxNode GetSymbolDeclarationSyntax(SyntaxReference reference, CancellationToken cancellationToken) => reference.GetSyntax(cancellationToken); protected override OneOrMany<(ISymbol? oldSymbol, ISymbol? newSymbol, EditKind editKind)> GetSymbolEdits( EditKind editKind, SyntaxNode? oldNode, SyntaxNode? newNode, SemanticModel? oldModel, SemanticModel newModel, IReadOnlyDictionary<SyntaxNode, EditKind> editMap, CancellationToken cancellationToken) { var oldSymbol = (oldNode != null) ? GetSymbolForEdit(oldNode, oldModel!, cancellationToken) : null; var newSymbol = (newNode != null) ? GetSymbolForEdit(newNode, newModel, cancellationToken) : null; switch (editKind) { case EditKind.Update: Contract.ThrowIfNull(oldNode); Contract.ThrowIfNull(newNode); Contract.ThrowIfNull(oldModel); // Certain updates of a property/indexer node affects its accessors. // Return all affected symbols for these updates. // 1) Old or new property/indexer has an expression body: // int this[...] => expr; // int this[...] { get => expr; } // int P => expr; // int P { get => expr; } = init if (oldNode is PropertyDeclarationSyntax { ExpressionBody: not null } or IndexerDeclarationSyntax { ExpressionBody: not null } || newNode is PropertyDeclarationSyntax { ExpressionBody: not null } or IndexerDeclarationSyntax { ExpressionBody: not null }) { Debug.Assert(oldSymbol is IPropertySymbol); Debug.Assert(newSymbol is IPropertySymbol); var oldGetterSymbol = ((IPropertySymbol)oldSymbol).GetMethod; var newGetterSymbol = ((IPropertySymbol)newSymbol).GetMethod; return OneOrMany.Create(ImmutableArray.Create((oldSymbol, newSymbol, editKind), (oldGetterSymbol, newGetterSymbol, editKind))); } // 2) Property/indexer declarations differ in readonly keyword. if (oldNode is PropertyDeclarationSyntax oldProperty && newNode is PropertyDeclarationSyntax newProperty && DiffersInReadOnlyModifier(oldProperty.Modifiers, newProperty.Modifiers) || oldNode is IndexerDeclarationSyntax oldIndexer && newNode is IndexerDeclarationSyntax newIndexer && DiffersInReadOnlyModifier(oldIndexer.Modifiers, newIndexer.Modifiers)) { Debug.Assert(oldSymbol is IPropertySymbol); Debug.Assert(newSymbol is IPropertySymbol); var oldPropertySymbol = (IPropertySymbol)oldSymbol; var newPropertySymbol = (IPropertySymbol)newSymbol; using var _ = ArrayBuilder<(ISymbol?, ISymbol?, EditKind)>.GetInstance(out var builder); builder.Add((oldPropertySymbol, newPropertySymbol, editKind)); if (oldPropertySymbol.GetMethod != null && newPropertySymbol.GetMethod != null && oldPropertySymbol.GetMethod.IsReadOnly != newPropertySymbol.GetMethod.IsReadOnly) { builder.Add((oldPropertySymbol.GetMethod, newPropertySymbol.GetMethod, editKind)); } if (oldPropertySymbol.SetMethod != null && newPropertySymbol.SetMethod != null && oldPropertySymbol.SetMethod.IsReadOnly != newPropertySymbol.SetMethod.IsReadOnly) { builder.Add((oldPropertySymbol.SetMethod, newPropertySymbol.SetMethod, editKind)); } return OneOrMany.Create(builder.ToImmutable()); } static bool DiffersInReadOnlyModifier(SyntaxTokenList oldModifiers, SyntaxTokenList newModifiers) => (oldModifiers.IndexOf(SyntaxKind.ReadOnlyKeyword) >= 0) != (newModifiers.IndexOf(SyntaxKind.ReadOnlyKeyword) >= 0); // Change in attributes or modifiers of a field affects all its variable declarations. if (oldNode is BaseFieldDeclarationSyntax oldField && newNode is BaseFieldDeclarationSyntax newField) { return GetFieldSymbolUpdates(oldField.Declaration.Variables, newField.Declaration.Variables); } // Chnage in type of a field affects all its variable declarations. if (oldNode is VariableDeclarationSyntax oldVariableDeclaration && newNode is VariableDeclarationSyntax newVariableDeclaration) { return GetFieldSymbolUpdates(oldVariableDeclaration.Variables, newVariableDeclaration.Variables); } OneOrMany<(ISymbol?, ISymbol?, EditKind)> GetFieldSymbolUpdates(SeparatedSyntaxList<VariableDeclaratorSyntax> oldVariables, SeparatedSyntaxList<VariableDeclaratorSyntax> newVariables) { if (oldVariables.Count == 1 && newVariables.Count == 1) { return OneOrMany.Create((oldModel.GetDeclaredSymbol(oldVariables[0], cancellationToken), newModel.GetDeclaredSymbol(newVariables[0], cancellationToken), EditKind.Update)); } var result = from oldVariable in oldVariables join newVariable in newVariables on oldVariable.Identifier.Text equals newVariable.Identifier.Text select (oldModel.GetDeclaredSymbol(oldVariable, cancellationToken), newModel.GetDeclaredSymbol(newVariable, cancellationToken), EditKind.Update); return OneOrMany.Create(result.ToImmutableArray()); } break; case EditKind.Delete: case EditKind.Insert: var node = oldNode ?? newNode; // If the entire block-bodied property/indexer is deleted/inserted (accessors and the list they are contained in), // ignore this edit. We will have a semantic edit for the property/indexer itself. if (node.IsKind(SyntaxKind.GetAccessorDeclaration)) { Debug.Assert(node.Parent.IsKind(SyntaxKind.AccessorList)); if (HasEdit(editMap, node.Parent, editKind) && !HasEdit(editMap, node.Parent.Parent, editKind)) { return OneOrMany<(ISymbol?, ISymbol?, EditKind)>.Empty; } } // Inserting/deleting an expression-bodied property/indexer affects two symbols: // the property/indexer itself and the getter. // int this[...] => expr; // int P => expr; if (node is PropertyDeclarationSyntax { ExpressionBody: not null } or IndexerDeclarationSyntax { ExpressionBody: not null }) { var oldGetterSymbol = ((IPropertySymbol?)oldSymbol)?.GetMethod; var newGetterSymbol = ((IPropertySymbol?)newSymbol)?.GetMethod; return OneOrMany.Create(ImmutableArray.Create((oldSymbol, newSymbol, editKind), (oldGetterSymbol, newGetterSymbol, editKind))); } // Inserting/deleting a type parameter constraint should result in an update of the corresponding type parameter symbol: if (node.IsKind(SyntaxKind.TypeParameterConstraintClause)) { return OneOrMany.Create(ImmutableArray.Create((oldSymbol, newSymbol, EditKind.Update))); } // Inserting/deleting a global statement should result in an update of the implicit main method: if (node.IsKind(SyntaxKind.GlobalStatement)) { return OneOrMany.Create(ImmutableArray.Create((oldSymbol, newSymbol, EditKind.Update))); } break; } return (editKind == EditKind.Delete ? oldSymbol : newSymbol) is null ? OneOrMany<(ISymbol?, ISymbol?, EditKind)>.Empty : new OneOrMany<(ISymbol?, ISymbol?, EditKind)>((oldSymbol, newSymbol, editKind)); } private static ISymbol? GetSymbolForEdit( SyntaxNode node, SemanticModel model, CancellationToken cancellationToken) { if (node.IsKind(SyntaxKind.UsingDirective, SyntaxKind.NamespaceDeclaration, SyntaxKind.FileScopedNamespaceDeclaration)) { return null; } if (node.IsKind(SyntaxKind.TypeParameterConstraintClause)) { var constraintClause = (TypeParameterConstraintClauseSyntax)node; var symbolInfo = model.GetSymbolInfo(constraintClause.Name, cancellationToken); return symbolInfo.Symbol; } // Top level code always lives in a synthesized Main method if (node.IsKind(SyntaxKind.GlobalStatement)) { return model.GetEnclosingSymbol(node.SpanStart, cancellationToken); } var symbol = model.GetDeclaredSymbol(node, cancellationToken); // TODO: this is incorrect (https://github.com/dotnet/roslyn/issues/54800) // Ignore partial method definition parts. // Partial method that does not have implementation part is not emitted to metadata. // Partial method without a definition part is a compilation error. if (symbol is IMethodSymbol { IsPartialDefinition: true }) { return null; } return symbol; } internal override bool ContainsLambda(SyntaxNode declaration) => declaration.DescendantNodes().Any(LambdaUtilities.IsLambda); internal override bool IsLambda(SyntaxNode node) => LambdaUtilities.IsLambda(node); internal override bool IsLocalFunction(SyntaxNode node) => node.IsKind(SyntaxKind.LocalFunctionStatement); internal override bool IsNestedFunction(SyntaxNode node) => node is AnonymousFunctionExpressionSyntax or LocalFunctionStatementSyntax; internal override bool TryGetLambdaBodies(SyntaxNode node, [NotNullWhen(true)] out SyntaxNode? body1, out SyntaxNode? body2) => LambdaUtilities.TryGetLambdaBodies(node, out body1, out body2); internal override SyntaxNode GetLambda(SyntaxNode lambdaBody) => LambdaUtilities.GetLambda(lambdaBody); internal override IMethodSymbol GetLambdaExpressionSymbol(SemanticModel model, SyntaxNode lambdaExpression, CancellationToken cancellationToken) { var bodyExpression = LambdaUtilities.GetNestedFunctionBody(lambdaExpression); return (IMethodSymbol)model.GetRequiredEnclosingSymbol(bodyExpression.SpanStart, cancellationToken); } internal override SyntaxNode? GetContainingQueryExpression(SyntaxNode node) => node.FirstAncestorOrSelf<QueryExpressionSyntax>(); internal override bool QueryClauseLambdasTypeEquivalent(SemanticModel oldModel, SyntaxNode oldNode, SemanticModel newModel, SyntaxNode newNode, CancellationToken cancellationToken) { switch (oldNode.Kind()) { case SyntaxKind.FromClause: case SyntaxKind.LetClause: case SyntaxKind.WhereClause: case SyntaxKind.OrderByClause: case SyntaxKind.JoinClause: var oldQueryClauseInfo = oldModel.GetQueryClauseInfo((QueryClauseSyntax)oldNode, cancellationToken); var newQueryClauseInfo = newModel.GetQueryClauseInfo((QueryClauseSyntax)newNode, cancellationToken); return MemberSignaturesEquivalent(oldQueryClauseInfo.CastInfo.Symbol, newQueryClauseInfo.CastInfo.Symbol) && MemberSignaturesEquivalent(oldQueryClauseInfo.OperationInfo.Symbol, newQueryClauseInfo.OperationInfo.Symbol); case SyntaxKind.AscendingOrdering: case SyntaxKind.DescendingOrdering: var oldOrderingInfo = oldModel.GetSymbolInfo(oldNode, cancellationToken); var newOrderingInfo = newModel.GetSymbolInfo(newNode, cancellationToken); return MemberSignaturesEquivalent(oldOrderingInfo.Symbol, newOrderingInfo.Symbol); case SyntaxKind.SelectClause: var oldSelectInfo = oldModel.GetSymbolInfo(oldNode, cancellationToken); var newSelectInfo = newModel.GetSymbolInfo(newNode, cancellationToken); // Changing reduced select clause to a non-reduced form or vice versa // adds/removes a call to Select method, which is a supported change. return oldSelectInfo.Symbol == null || newSelectInfo.Symbol == null || MemberSignaturesEquivalent(oldSelectInfo.Symbol, newSelectInfo.Symbol); case SyntaxKind.GroupClause: var oldGroupByInfo = oldModel.GetSymbolInfo(oldNode, cancellationToken); var newGroupByInfo = newModel.GetSymbolInfo(newNode, cancellationToken); return MemberSignaturesEquivalent(oldGroupByInfo.Symbol, newGroupByInfo.Symbol, GroupBySignatureComparer); default: return true; } } private static bool GroupBySignatureComparer(ImmutableArray<IParameterSymbol> oldParameters, ITypeSymbol oldReturnType, ImmutableArray<IParameterSymbol> newParameters, ITypeSymbol newReturnType) { // C# spec paragraph 7.16.2.6 "Groupby clauses": // // A query expression of the form // from x in e group v by k // is translated into // (e).GroupBy(x => k, x => v) // except when v is the identifier x, the translation is // (e).GroupBy(x => k) // // Possible signatures: // C<G<K, T>> GroupBy<K>(Func<T, K> keySelector); // C<G<K, E>> GroupBy<K, E>(Func<T, K> keySelector, Func<T, E> elementSelector); if (!TypesEquivalent(oldReturnType, newReturnType, exact: false)) { return false; } Debug.Assert(oldParameters.Length == 1 || oldParameters.Length == 2); Debug.Assert(newParameters.Length == 1 || newParameters.Length == 2); // The types of the lambdas have to be the same if present. // The element selector may be added/removed. if (!ParameterTypesEquivalent(oldParameters[0], newParameters[0], exact: false)) { return false; } if (oldParameters.Length == newParameters.Length && newParameters.Length == 2) { return ParameterTypesEquivalent(oldParameters[1], newParameters[1], exact: false); } return true; } #endregion #region Diagnostic Info protected override SymbolDisplayFormat ErrorDisplayFormat => SymbolDisplayFormat.CSharpErrorMessageFormat; protected override TextSpan? TryGetDiagnosticSpan(SyntaxNode node, EditKind editKind) => TryGetDiagnosticSpanImpl(node, editKind); internal static new TextSpan GetDiagnosticSpan(SyntaxNode node, EditKind editKind) => TryGetDiagnosticSpanImpl(node, editKind) ?? node.Span; private static TextSpan? TryGetDiagnosticSpanImpl(SyntaxNode node, EditKind editKind) => TryGetDiagnosticSpanImpl(node.Kind(), node, editKind); // internal for testing; kind is passed explicitly for testing as well internal static TextSpan? TryGetDiagnosticSpanImpl(SyntaxKind kind, SyntaxNode node, EditKind editKind) { switch (kind) { case SyntaxKind.CompilationUnit: return default(TextSpan); case SyntaxKind.GlobalStatement: return node.Span; case SyntaxKind.ExternAliasDirective: case SyntaxKind.UsingDirective: return node.Span; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: var ns = (BaseNamespaceDeclarationSyntax)node; return TextSpan.FromBounds(ns.NamespaceKeyword.SpanStart, ns.Name.Span.End); case SyntaxKind.ClassDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: var typeDeclaration = (TypeDeclarationSyntax)node; return GetDiagnosticSpan(typeDeclaration.Modifiers, typeDeclaration.Keyword, typeDeclaration.TypeParameterList ?? (SyntaxNodeOrToken)typeDeclaration.Identifier); case SyntaxKind.EnumDeclaration: var enumDeclaration = (EnumDeclarationSyntax)node; return GetDiagnosticSpan(enumDeclaration.Modifiers, enumDeclaration.EnumKeyword, enumDeclaration.Identifier); case SyntaxKind.DelegateDeclaration: var delegateDeclaration = (DelegateDeclarationSyntax)node; return GetDiagnosticSpan(delegateDeclaration.Modifiers, delegateDeclaration.DelegateKeyword, delegateDeclaration.ParameterList); case SyntaxKind.FieldDeclaration: var fieldDeclaration = (BaseFieldDeclarationSyntax)node; return GetDiagnosticSpan(fieldDeclaration.Modifiers, fieldDeclaration.Declaration, fieldDeclaration.Declaration); case SyntaxKind.EventFieldDeclaration: var eventFieldDeclaration = (EventFieldDeclarationSyntax)node; return GetDiagnosticSpan(eventFieldDeclaration.Modifiers, eventFieldDeclaration.EventKeyword, eventFieldDeclaration.Declaration); case SyntaxKind.VariableDeclaration: return TryGetDiagnosticSpanImpl(node.Parent!, editKind); case SyntaxKind.VariableDeclarator: return node.Span; case SyntaxKind.MethodDeclaration: var methodDeclaration = (MethodDeclarationSyntax)node; return GetDiagnosticSpan(methodDeclaration.Modifiers, methodDeclaration.ReturnType, methodDeclaration.ParameterList); case SyntaxKind.ConversionOperatorDeclaration: var conversionOperatorDeclaration = (ConversionOperatorDeclarationSyntax)node; return GetDiagnosticSpan(conversionOperatorDeclaration.Modifiers, conversionOperatorDeclaration.ImplicitOrExplicitKeyword, conversionOperatorDeclaration.ParameterList); case SyntaxKind.OperatorDeclaration: var operatorDeclaration = (OperatorDeclarationSyntax)node; return GetDiagnosticSpan(operatorDeclaration.Modifiers, operatorDeclaration.ReturnType, operatorDeclaration.ParameterList); case SyntaxKind.ConstructorDeclaration: var constructorDeclaration = (ConstructorDeclarationSyntax)node; return GetDiagnosticSpan(constructorDeclaration.Modifiers, constructorDeclaration.Identifier, constructorDeclaration.ParameterList); case SyntaxKind.DestructorDeclaration: var destructorDeclaration = (DestructorDeclarationSyntax)node; return GetDiagnosticSpan(destructorDeclaration.Modifiers, destructorDeclaration.TildeToken, destructorDeclaration.ParameterList); case SyntaxKind.PropertyDeclaration: var propertyDeclaration = (PropertyDeclarationSyntax)node; return GetDiagnosticSpan(propertyDeclaration.Modifiers, propertyDeclaration.Type, propertyDeclaration.Identifier); case SyntaxKind.IndexerDeclaration: var indexerDeclaration = (IndexerDeclarationSyntax)node; return GetDiagnosticSpan(indexerDeclaration.Modifiers, indexerDeclaration.Type, indexerDeclaration.ParameterList); case SyntaxKind.EventDeclaration: var eventDeclaration = (EventDeclarationSyntax)node; return GetDiagnosticSpan(eventDeclaration.Modifiers, eventDeclaration.EventKeyword, eventDeclaration.Identifier); case SyntaxKind.EnumMemberDeclaration: return node.Span; case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: case SyntaxKind.UnknownAccessorDeclaration: var accessorDeclaration = (AccessorDeclarationSyntax)node; return GetDiagnosticSpan(accessorDeclaration.Modifiers, accessorDeclaration.Keyword, accessorDeclaration.Keyword); case SyntaxKind.TypeParameterConstraintClause: var constraint = (TypeParameterConstraintClauseSyntax)node; return TextSpan.FromBounds(constraint.WhereKeyword.SpanStart, constraint.Constraints.Last().Span.End); case SyntaxKind.TypeParameter: var typeParameter = (TypeParameterSyntax)node; return typeParameter.Identifier.Span; case SyntaxKind.AccessorList: case SyntaxKind.TypeParameterList: case SyntaxKind.ParameterList: case SyntaxKind.BracketedParameterList: if (editKind == EditKind.Delete) { return TryGetDiagnosticSpanImpl(node.Parent!, editKind); } else { return node.Span; } case SyntaxKind.Parameter: var parameter = (ParameterSyntax)node; // Lambda parameters don't have types or modifiers, so the parameter is the only node var startNode = parameter.Type ?? (SyntaxNode)parameter; return GetDiagnosticSpan(parameter.Modifiers, startNode, parameter); case SyntaxKind.AttributeList: var attributeList = (AttributeListSyntax)node; return attributeList.Span; case SyntaxKind.Attribute: return node.Span; case SyntaxKind.ArrowExpressionClause: return TryGetDiagnosticSpanImpl(node.Parent!, editKind); // We only need a diagnostic span if reporting an error for a child statement. // The following statements may have child statements. case SyntaxKind.Block: return ((BlockSyntax)node).OpenBraceToken.Span; case SyntaxKind.UsingStatement: var usingStatement = (UsingStatementSyntax)node; return TextSpan.FromBounds(usingStatement.UsingKeyword.SpanStart, usingStatement.CloseParenToken.Span.End); case SyntaxKind.FixedStatement: var fixedStatement = (FixedStatementSyntax)node; return TextSpan.FromBounds(fixedStatement.FixedKeyword.SpanStart, fixedStatement.CloseParenToken.Span.End); case SyntaxKind.LockStatement: var lockStatement = (LockStatementSyntax)node; return TextSpan.FromBounds(lockStatement.LockKeyword.SpanStart, lockStatement.CloseParenToken.Span.End); case SyntaxKind.StackAllocArrayCreationExpression: return ((StackAllocArrayCreationExpressionSyntax)node).StackAllocKeyword.Span; case SyntaxKind.ImplicitStackAllocArrayCreationExpression: return ((ImplicitStackAllocArrayCreationExpressionSyntax)node).StackAllocKeyword.Span; case SyntaxKind.TryStatement: return ((TryStatementSyntax)node).TryKeyword.Span; case SyntaxKind.CatchClause: return ((CatchClauseSyntax)node).CatchKeyword.Span; case SyntaxKind.CatchDeclaration: case SyntaxKind.CatchFilterClause: return node.Span; case SyntaxKind.FinallyClause: return ((FinallyClauseSyntax)node).FinallyKeyword.Span; case SyntaxKind.IfStatement: var ifStatement = (IfStatementSyntax)node; return TextSpan.FromBounds(ifStatement.IfKeyword.SpanStart, ifStatement.CloseParenToken.Span.End); case SyntaxKind.ElseClause: return ((ElseClauseSyntax)node).ElseKeyword.Span; case SyntaxKind.SwitchStatement: var switchStatement = (SwitchStatementSyntax)node; return TextSpan.FromBounds(switchStatement.SwitchKeyword.SpanStart, (switchStatement.CloseParenToken != default) ? switchStatement.CloseParenToken.Span.End : switchStatement.Expression.Span.End); case SyntaxKind.SwitchSection: return ((SwitchSectionSyntax)node).Labels.Last().Span; case SyntaxKind.WhileStatement: var whileStatement = (WhileStatementSyntax)node; return TextSpan.FromBounds(whileStatement.WhileKeyword.SpanStart, whileStatement.CloseParenToken.Span.End); case SyntaxKind.DoStatement: return ((DoStatementSyntax)node).DoKeyword.Span; case SyntaxKind.ForStatement: var forStatement = (ForStatementSyntax)node; return TextSpan.FromBounds(forStatement.ForKeyword.SpanStart, forStatement.CloseParenToken.Span.End); case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: var commonForEachStatement = (CommonForEachStatementSyntax)node; return TextSpan.FromBounds( (commonForEachStatement.AwaitKeyword.Span.Length > 0) ? commonForEachStatement.AwaitKeyword.SpanStart : commonForEachStatement.ForEachKeyword.SpanStart, commonForEachStatement.CloseParenToken.Span.End); case SyntaxKind.LabeledStatement: return ((LabeledStatementSyntax)node).Identifier.Span; case SyntaxKind.CheckedStatement: case SyntaxKind.UncheckedStatement: return ((CheckedStatementSyntax)node).Keyword.Span; case SyntaxKind.UnsafeStatement: return ((UnsafeStatementSyntax)node).UnsafeKeyword.Span; case SyntaxKind.LocalFunctionStatement: var lfd = (LocalFunctionStatementSyntax)node; return lfd.Identifier.Span; case SyntaxKind.YieldBreakStatement: case SyntaxKind.YieldReturnStatement: case SyntaxKind.ReturnStatement: case SyntaxKind.ThrowStatement: case SyntaxKind.ExpressionStatement: case SyntaxKind.EmptyStatement: case SyntaxKind.GotoStatement: case SyntaxKind.GotoCaseStatement: case SyntaxKind.GotoDefaultStatement: case SyntaxKind.BreakStatement: case SyntaxKind.ContinueStatement: return node.Span; case SyntaxKind.LocalDeclarationStatement: var localDeclarationStatement = (LocalDeclarationStatementSyntax)node; return CombineSpans(localDeclarationStatement.AwaitKeyword.Span, localDeclarationStatement.UsingKeyword.Span, node.Span); case SyntaxKind.AwaitExpression: return ((AwaitExpressionSyntax)node).AwaitKeyword.Span; case SyntaxKind.AnonymousObjectCreationExpression: return ((AnonymousObjectCreationExpressionSyntax)node).NewKeyword.Span; case SyntaxKind.ParenthesizedLambdaExpression: return ((ParenthesizedLambdaExpressionSyntax)node).ParameterList.Span; case SyntaxKind.SimpleLambdaExpression: return ((SimpleLambdaExpressionSyntax)node).Parameter.Span; case SyntaxKind.AnonymousMethodExpression: return ((AnonymousMethodExpressionSyntax)node).DelegateKeyword.Span; case SyntaxKind.QueryExpression: return ((QueryExpressionSyntax)node).FromClause.FromKeyword.Span; case SyntaxKind.QueryBody: var queryBody = (QueryBodySyntax)node; return TryGetDiagnosticSpanImpl(queryBody.Clauses.FirstOrDefault() ?? queryBody.Parent!, editKind); case SyntaxKind.QueryContinuation: return ((QueryContinuationSyntax)node).IntoKeyword.Span; case SyntaxKind.FromClause: return ((FromClauseSyntax)node).FromKeyword.Span; case SyntaxKind.JoinClause: return ((JoinClauseSyntax)node).JoinKeyword.Span; case SyntaxKind.JoinIntoClause: return ((JoinIntoClauseSyntax)node).IntoKeyword.Span; case SyntaxKind.LetClause: return ((LetClauseSyntax)node).LetKeyword.Span; case SyntaxKind.WhereClause: return ((WhereClauseSyntax)node).WhereKeyword.Span; case SyntaxKind.OrderByClause: return ((OrderByClauseSyntax)node).OrderByKeyword.Span; case SyntaxKind.AscendingOrdering: case SyntaxKind.DescendingOrdering: return node.Span; case SyntaxKind.SelectClause: return ((SelectClauseSyntax)node).SelectKeyword.Span; case SyntaxKind.GroupClause: return ((GroupClauseSyntax)node).GroupKeyword.Span; case SyntaxKind.IsPatternExpression: case SyntaxKind.TupleType: case SyntaxKind.TupleExpression: case SyntaxKind.DeclarationExpression: case SyntaxKind.RefType: case SyntaxKind.RefExpression: case SyntaxKind.DeclarationPattern: case SyntaxKind.SimpleAssignmentExpression: case SyntaxKind.WhenClause: case SyntaxKind.SingleVariableDesignation: case SyntaxKind.CasePatternSwitchLabel: return node.Span; case SyntaxKind.SwitchExpression: return ((SwitchExpressionSyntax)node).SwitchKeyword.Span; case SyntaxKind.SwitchExpressionArm: return ((SwitchExpressionArmSyntax)node).EqualsGreaterThanToken.Span; default: return null; } } private static TextSpan GetDiagnosticSpan(SyntaxTokenList modifiers, SyntaxNodeOrToken start, SyntaxNodeOrToken end) => TextSpan.FromBounds((modifiers.Count != 0) ? modifiers.First().SpanStart : start.SpanStart, end.Span.End); private static TextSpan CombineSpans(TextSpan first, TextSpan second, TextSpan defaultSpan) => (first.Length > 0 && second.Length > 0) ? TextSpan.FromBounds(first.Start, second.End) : (first.Length > 0) ? first : (second.Length > 0) ? second : defaultSpan; internal override TextSpan GetLambdaParameterDiagnosticSpan(SyntaxNode lambda, int ordinal) { Debug.Assert(ordinal >= 0); switch (lambda.Kind()) { case SyntaxKind.ParenthesizedLambdaExpression: return ((ParenthesizedLambdaExpressionSyntax)lambda).ParameterList.Parameters[ordinal].Identifier.Span; case SyntaxKind.SimpleLambdaExpression: Debug.Assert(ordinal == 0); return ((SimpleLambdaExpressionSyntax)lambda).Parameter.Identifier.Span; case SyntaxKind.AnonymousMethodExpression: // since we are given a parameter ordinal there has to be a parameter list: return ((AnonymousMethodExpressionSyntax)lambda).ParameterList!.Parameters[ordinal].Identifier.Span; default: return lambda.Span; } } internal override string GetDisplayName(INamedTypeSymbol symbol) => symbol.TypeKind switch { TypeKind.Struct => symbol.IsRecord ? CSharpFeaturesResources.record_struct : CSharpFeaturesResources.struct_, TypeKind.Class => symbol.IsRecord ? CSharpFeaturesResources.record_ : FeaturesResources.class_, _ => base.GetDisplayName(symbol) }; internal override string GetDisplayName(IPropertySymbol symbol) => symbol.IsIndexer ? CSharpFeaturesResources.indexer : base.GetDisplayName(symbol); internal override string GetDisplayName(IMethodSymbol symbol) => symbol.MethodKind switch { MethodKind.PropertyGet => symbol.AssociatedSymbol is IPropertySymbol { IsIndexer: true } ? CSharpFeaturesResources.indexer_getter : CSharpFeaturesResources.property_getter, MethodKind.PropertySet => symbol.AssociatedSymbol is IPropertySymbol { IsIndexer: true } ? CSharpFeaturesResources.indexer_setter : CSharpFeaturesResources.property_setter, MethodKind.StaticConstructor => FeaturesResources.static_constructor, MethodKind.Destructor => CSharpFeaturesResources.destructor, MethodKind.Conversion => CSharpFeaturesResources.conversion_operator, MethodKind.LocalFunction => FeaturesResources.local_function, _ => base.GetDisplayName(symbol) }; protected override string? TryGetDisplayName(SyntaxNode node, EditKind editKind) => TryGetDisplayNameImpl(node, editKind); internal static new string? GetDisplayName(SyntaxNode node, EditKind editKind) => TryGetDisplayNameImpl(node, editKind) ?? throw ExceptionUtilities.UnexpectedValue(node.Kind()); internal static string? TryGetDisplayNameImpl(SyntaxNode node, EditKind editKind) { switch (node.Kind()) { // top-level case SyntaxKind.CompilationUnit: case SyntaxKind.GlobalStatement: return CSharpFeaturesResources.global_statement; case SyntaxKind.ExternAliasDirective: return CSharpFeaturesResources.extern_alias; case SyntaxKind.UsingDirective: // Dev12 distinguishes using alias from using namespace and reports different errors for removing alias. // None of these changes are allowed anyways, so let's keep it simple. return CSharpFeaturesResources.using_directive; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: return FeaturesResources.namespace_; case SyntaxKind.ClassDeclaration: return FeaturesResources.class_; case SyntaxKind.StructDeclaration: return CSharpFeaturesResources.struct_; case SyntaxKind.InterfaceDeclaration: return FeaturesResources.interface_; case SyntaxKind.RecordDeclaration: return CSharpFeaturesResources.record_; case SyntaxKind.RecordStructDeclaration: return CSharpFeaturesResources.record_struct; case SyntaxKind.EnumDeclaration: return FeaturesResources.enum_; case SyntaxKind.DelegateDeclaration: return FeaturesResources.delegate_; case SyntaxKind.FieldDeclaration: var declaration = (FieldDeclarationSyntax)node; return declaration.Modifiers.Any(SyntaxKind.ConstKeyword) ? FeaturesResources.const_field : FeaturesResources.field; case SyntaxKind.EventFieldDeclaration: return CSharpFeaturesResources.event_field; case SyntaxKind.VariableDeclaration: case SyntaxKind.VariableDeclarator: return TryGetDisplayNameImpl(node.Parent!, editKind); case SyntaxKind.MethodDeclaration: return FeaturesResources.method; case SyntaxKind.ConversionOperatorDeclaration: return CSharpFeaturesResources.conversion_operator; case SyntaxKind.OperatorDeclaration: return FeaturesResources.operator_; case SyntaxKind.ConstructorDeclaration: var ctor = (ConstructorDeclarationSyntax)node; return ctor.Modifiers.Any(SyntaxKind.StaticKeyword) ? FeaturesResources.static_constructor : FeaturesResources.constructor; case SyntaxKind.DestructorDeclaration: return CSharpFeaturesResources.destructor; case SyntaxKind.PropertyDeclaration: return SyntaxUtilities.HasBackingField((PropertyDeclarationSyntax)node) ? FeaturesResources.auto_property : FeaturesResources.property_; case SyntaxKind.IndexerDeclaration: return CSharpFeaturesResources.indexer; case SyntaxKind.EventDeclaration: return FeaturesResources.event_; case SyntaxKind.EnumMemberDeclaration: return FeaturesResources.enum_value; case SyntaxKind.GetAccessorDeclaration: if (node.Parent!.Parent!.IsKind(SyntaxKind.PropertyDeclaration)) { return CSharpFeaturesResources.property_getter; } else { RoslynDebug.Assert(node.Parent.Parent.IsKind(SyntaxKind.IndexerDeclaration)); return CSharpFeaturesResources.indexer_getter; } case SyntaxKind.InitAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: if (node.Parent!.Parent!.IsKind(SyntaxKind.PropertyDeclaration)) { return CSharpFeaturesResources.property_setter; } else { RoslynDebug.Assert(node.Parent.Parent.IsKind(SyntaxKind.IndexerDeclaration)); return CSharpFeaturesResources.indexer_setter; } case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return FeaturesResources.event_accessor; case SyntaxKind.ArrowExpressionClause: return node.Parent!.Kind() switch { SyntaxKind.PropertyDeclaration => CSharpFeaturesResources.property_getter, SyntaxKind.IndexerDeclaration => CSharpFeaturesResources.indexer_getter, _ => null }; case SyntaxKind.TypeParameterConstraintClause: return FeaturesResources.type_constraint; case SyntaxKind.TypeParameterList: case SyntaxKind.TypeParameter: return FeaturesResources.type_parameter; case SyntaxKind.Parameter: return FeaturesResources.parameter; case SyntaxKind.AttributeList: return FeaturesResources.attribute; case SyntaxKind.Attribute: return FeaturesResources.attribute; case SyntaxKind.AttributeTargetSpecifier: return CSharpFeaturesResources.attribute_target; // statement: case SyntaxKind.TryStatement: return CSharpFeaturesResources.try_block; case SyntaxKind.CatchClause: case SyntaxKind.CatchDeclaration: return CSharpFeaturesResources.catch_clause; case SyntaxKind.CatchFilterClause: return CSharpFeaturesResources.filter_clause; case SyntaxKind.FinallyClause: return CSharpFeaturesResources.finally_clause; case SyntaxKind.FixedStatement: return CSharpFeaturesResources.fixed_statement; case SyntaxKind.UsingStatement: return CSharpFeaturesResources.using_statement; case SyntaxKind.LockStatement: return CSharpFeaturesResources.lock_statement; case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: return CSharpFeaturesResources.foreach_statement; case SyntaxKind.CheckedStatement: return CSharpFeaturesResources.checked_statement; case SyntaxKind.UncheckedStatement: return CSharpFeaturesResources.unchecked_statement; case SyntaxKind.YieldBreakStatement: return CSharpFeaturesResources.yield_break_statement; case SyntaxKind.YieldReturnStatement: return CSharpFeaturesResources.yield_return_statement; case SyntaxKind.AwaitExpression: return CSharpFeaturesResources.await_expression; case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: return CSharpFeaturesResources.lambda; case SyntaxKind.AnonymousMethodExpression: return CSharpFeaturesResources.anonymous_method; case SyntaxKind.FromClause: return CSharpFeaturesResources.from_clause; case SyntaxKind.JoinClause: case SyntaxKind.JoinIntoClause: return CSharpFeaturesResources.join_clause; case SyntaxKind.LetClause: return CSharpFeaturesResources.let_clause; case SyntaxKind.WhereClause: return CSharpFeaturesResources.where_clause; case SyntaxKind.OrderByClause: case SyntaxKind.AscendingOrdering: case SyntaxKind.DescendingOrdering: return CSharpFeaturesResources.orderby_clause; case SyntaxKind.SelectClause: return CSharpFeaturesResources.select_clause; case SyntaxKind.GroupClause: return CSharpFeaturesResources.groupby_clause; case SyntaxKind.QueryBody: return CSharpFeaturesResources.query_body; case SyntaxKind.QueryContinuation: return CSharpFeaturesResources.into_clause; case SyntaxKind.IsPatternExpression: return CSharpFeaturesResources.is_pattern; case SyntaxKind.SimpleAssignmentExpression: if (((AssignmentExpressionSyntax)node).IsDeconstruction()) { return CSharpFeaturesResources.deconstruction; } else { throw ExceptionUtilities.UnexpectedValue(node.Kind()); } case SyntaxKind.TupleType: case SyntaxKind.TupleExpression: return CSharpFeaturesResources.tuple; case SyntaxKind.LocalFunctionStatement: return CSharpFeaturesResources.local_function; case SyntaxKind.DeclarationExpression: return CSharpFeaturesResources.out_var; case SyntaxKind.RefType: case SyntaxKind.RefExpression: return CSharpFeaturesResources.ref_local_or_expression; case SyntaxKind.SwitchStatement: return CSharpFeaturesResources.switch_statement; case SyntaxKind.LocalDeclarationStatement: if (((LocalDeclarationStatementSyntax)node).UsingKeyword.IsKind(SyntaxKind.UsingKeyword)) { return CSharpFeaturesResources.using_declaration; } return CSharpFeaturesResources.local_variable_declaration; default: return null; } } protected override string GetSuspensionPointDisplayName(SyntaxNode node, EditKind editKind) { switch (node.Kind()) { case SyntaxKind.ForEachStatement: Debug.Assert(((CommonForEachStatementSyntax)node).AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword)); return CSharpFeaturesResources.asynchronous_foreach_statement; case SyntaxKind.VariableDeclarator: RoslynDebug.Assert(((LocalDeclarationStatementSyntax)node.Parent!.Parent!).AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword)); return CSharpFeaturesResources.asynchronous_using_declaration; default: return base.GetSuspensionPointDisplayName(node, editKind); } } #endregion #region Top-Level Syntactic Rude Edits private readonly struct EditClassifier { private readonly CSharpEditAndContinueAnalyzer _analyzer; private readonly ArrayBuilder<RudeEditDiagnostic> _diagnostics; private readonly Match<SyntaxNode>? _match; private readonly SyntaxNode? _oldNode; private readonly SyntaxNode? _newNode; private readonly EditKind _kind; private readonly TextSpan? _span; public EditClassifier( CSharpEditAndContinueAnalyzer analyzer, ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode? oldNode, SyntaxNode? newNode, EditKind kind, Match<SyntaxNode>? match = null, TextSpan? span = null) { RoslynDebug.Assert(oldNode != null || newNode != null); // if the node is deleted we have map that can be used to closest new ancestor RoslynDebug.Assert(newNode != null || match != null); _analyzer = analyzer; _diagnostics = diagnostics; _oldNode = oldNode; _newNode = newNode; _kind = kind; _span = span; _match = match; } private void ReportError(RudeEditKind kind, SyntaxNode? spanNode = null, SyntaxNode? displayNode = null) { var span = (spanNode != null) ? GetDiagnosticSpan(spanNode, _kind) : GetSpan(); var node = displayNode ?? _newNode ?? _oldNode; var displayName = GetDisplayName(node!, _kind); _diagnostics.Add(new RudeEditDiagnostic(kind, span, node, arguments: new[] { displayName })); } private TextSpan GetSpan() { if (_span.HasValue) { return _span.Value; } if (_newNode == null) { return _analyzer.GetDeletedNodeDiagnosticSpan(_match!.Matches, _oldNode!); } return GetDiagnosticSpan(_newNode, _kind); } public void ClassifyEdit() { switch (_kind) { case EditKind.Delete: ClassifyDelete(_oldNode!); return; case EditKind.Update: ClassifyUpdate(_oldNode!, _newNode!); return; case EditKind.Move: ClassifyMove(_newNode!); return; case EditKind.Insert: ClassifyInsert(_newNode!); return; case EditKind.Reorder: ClassifyReorder(_newNode!); return; default: throw ExceptionUtilities.UnexpectedValue(_kind); } } private void ClassifyMove(SyntaxNode newNode) { if (newNode.IsKind(SyntaxKind.LocalFunctionStatement)) { return; } // We could perhaps allow moving a type declaration to a different namespace syntax node // as long as it represents semantically the same namespace as the one of the original type declaration. ReportError(RudeEditKind.Move); } private void ClassifyReorder(SyntaxNode newNode) { if (_newNode.IsKind(SyntaxKind.LocalFunctionStatement)) { return; } switch (newNode.Kind()) { case SyntaxKind.PropertyDeclaration: case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: case SyntaxKind.VariableDeclarator: // Maybe we could allow changing order of field declarations unless the containing type layout is sequential. ReportError(RudeEditKind.Move); return; case SyntaxKind.EnumMemberDeclaration: // To allow this change we would need to check that values of all fields of the enum // are preserved, or make sure we can update all method bodies that accessed those that changed. ReportError(RudeEditKind.Move); return; case SyntaxKind.TypeParameter: case SyntaxKind.Parameter: ReportError(RudeEditKind.Move); return; } } private void ClassifyInsert(SyntaxNode node) { switch (node.Kind()) { case SyntaxKind.ExternAliasDirective: case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: ReportError(RudeEditKind.Insert); return; case SyntaxKind.Attribute: case SyntaxKind.AttributeList: // To allow inserting of attributes we need to check if the inserted attribute // is a pseudo-custom attribute that CLR allows us to change, or if it is a compiler well-know attribute // that affects the generated IL, so we defer those checks until semantic analysis. // Unless the attribute is a module/assembly attribute if (node.IsParentKind(SyntaxKind.CompilationUnit) || node.Parent.IsParentKind(SyntaxKind.CompilationUnit)) { ReportError(RudeEditKind.Insert); } return; } } private void ClassifyDelete(SyntaxNode oldNode) { switch (oldNode.Kind()) { case SyntaxKind.ExternAliasDirective: case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: // To allow removal of declarations we would need to update method bodies that // were previously binding to them but now are binding to another symbol that was previously hidden. ReportError(RudeEditKind.Delete); return; case SyntaxKind.AttributeList: case SyntaxKind.Attribute: // To allow removal of attributes we need to check if the removed attribute // is a pseudo-custom attribute that CLR does not allow us to change, or if it is a compiler well-know attribute // that affects the generated IL, so we defer those checks until semantic analysis. // Unless the attribute is a module/assembly attribute if (oldNode.IsParentKind(SyntaxKind.CompilationUnit) || oldNode.Parent.IsParentKind(SyntaxKind.CompilationUnit)) { ReportError(RudeEditKind.Delete); } return; } } private void ClassifyUpdate(SyntaxNode oldNode, SyntaxNode newNode) { switch (newNode.Kind()) { case SyntaxKind.ExternAliasDirective: ReportError(RudeEditKind.Update); return; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: ClassifyUpdate((BaseNamespaceDeclarationSyntax)oldNode, (BaseNamespaceDeclarationSyntax)newNode); return; case SyntaxKind.Attribute: // To allow update of attributes we need to check if the updated attribute // is a pseudo-custom attribute that CLR allows us to change, or if it is a compiler well-know attribute // that affects the generated IL, so we defer those checks until semantic analysis. // Unless the attribute is a module/assembly attribute if (newNode.IsParentKind(SyntaxKind.CompilationUnit) || newNode.Parent.IsParentKind(SyntaxKind.CompilationUnit)) { ReportError(RudeEditKind.Update); } return; } } private void ClassifyUpdate(BaseNamespaceDeclarationSyntax oldNode, BaseNamespaceDeclarationSyntax newNode) { Debug.Assert(!SyntaxFactory.AreEquivalent(oldNode.Name, newNode.Name)); ReportError(RudeEditKind.Renamed); } public void ClassifyDeclarationBodyRudeUpdates(SyntaxNode newDeclarationOrBody) { foreach (var node in newDeclarationOrBody.DescendantNodesAndSelf(LambdaUtilities.IsNotLambda)) { switch (node.Kind()) { case SyntaxKind.StackAllocArrayCreationExpression: case SyntaxKind.ImplicitStackAllocArrayCreationExpression: ReportError(RudeEditKind.StackAllocUpdate, node, _newNode); return; } } } } internal override void ReportTopLevelSyntacticRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, Edit<SyntaxNode> edit, Dictionary<SyntaxNode, EditKind> editMap) { if (HasParentEdit(editMap, edit)) { return; } var classifier = new EditClassifier(this, diagnostics, edit.OldNode, edit.NewNode, edit.Kind, match); classifier.ClassifyEdit(); } internal override void ReportMemberBodyUpdateRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode newMember, TextSpan? span) { var classifier = new EditClassifier(this, diagnostics, oldNode: null, newMember, EditKind.Update, span: span); classifier.ClassifyDeclarationBodyRudeUpdates(newMember); } #endregion #region Semantic Rude Edits internal override void ReportInsertedMemberSymbolRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol newSymbol, SyntaxNode newNode, bool insertingIntoExistingContainingType) { var rudeEditKind = newSymbol switch { // Inserting extern member into a new or existing type is not allowed. { IsExtern: true } => RudeEditKind.InsertExtern, // All rude edits below only apply when inserting into an existing type (not when the type itself is inserted): _ when !insertingIntoExistingContainingType => RudeEditKind.None, // Inserting a member into an existing generic type is not allowed. { ContainingType: { Arity: > 0 } } and not INamedTypeSymbol => RudeEditKind.InsertIntoGenericType, // Inserting virtual or interface member into an existing type is not allowed. { IsVirtual: true } or { IsOverride: true } or { IsAbstract: true } and not INamedTypeSymbol => RudeEditKind.InsertVirtual, // Inserting generic method into an existing type is not allowed. IMethodSymbol { Arity: > 0 } => RudeEditKind.InsertGenericMethod, // Inserting destructor to an existing type is not allowed. IMethodSymbol { MethodKind: MethodKind.Destructor } => RudeEditKind.Insert, // Inserting operator to an existing type is not allowed. IMethodSymbol { MethodKind: MethodKind.Conversion or MethodKind.UserDefinedOperator } => RudeEditKind.InsertOperator, // Inserting a method that explictly implements an interface method into an existing type is not allowed. IMethodSymbol { ExplicitInterfaceImplementations: { IsEmpty: false } } => RudeEditKind.InsertMethodWithExplicitInterfaceSpecifier, // TODO: Inserting non-virtual member to an interface (https://github.com/dotnet/roslyn/issues/37128) { ContainingType: { TypeKind: TypeKind.Interface } } and not INamedTypeSymbol => RudeEditKind.InsertIntoInterface, // Inserting a field into an enum: #pragma warning disable format // https://github.com/dotnet/roslyn/issues/54759 IFieldSymbol { ContainingType.TypeKind: TypeKind.Enum } => RudeEditKind.Insert, #pragma warning restore format _ => RudeEditKind.None }; if (rudeEditKind != RudeEditKind.None) { diagnostics.Add(new RudeEditDiagnostic( rudeEditKind, GetDiagnosticSpan(newNode, EditKind.Insert), newNode, arguments: new[] { GetDisplayName(newNode, EditKind.Insert) })); } } #endregion #region Exception Handling Rude Edits /// <summary> /// Return nodes that represent exception handlers encompassing the given active statement node. /// </summary> protected override List<SyntaxNode> GetExceptionHandlingAncestors(SyntaxNode node, bool isNonLeaf) { var result = new List<SyntaxNode>(); var current = node; while (current != null) { var kind = current.Kind(); switch (kind) { case SyntaxKind.TryStatement: if (isNonLeaf) { result.Add(current); } break; case SyntaxKind.CatchClause: case SyntaxKind.FinallyClause: result.Add(current); // skip try: RoslynDebug.Assert(current.Parent is object); RoslynDebug.Assert(current.Parent.Kind() == SyntaxKind.TryStatement); current = current.Parent; break; // stop at type declaration: case SyntaxKind.ClassDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: return result; } // stop at lambda: if (LambdaUtilities.IsLambda(current)) { return result; } current = current.Parent; } return result; } internal override void ReportEnclosingExceptionHandlingRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, IEnumerable<Edit<SyntaxNode>> exceptionHandlingEdits, SyntaxNode oldStatement, TextSpan newStatementSpan) { foreach (var edit in exceptionHandlingEdits) { // try/catch/finally have distinct labels so only the nodes of the same kind may match: Debug.Assert(edit.Kind != EditKind.Update || edit.OldNode.RawKind == edit.NewNode.RawKind); if (edit.Kind != EditKind.Update || !AreExceptionClausesEquivalent(edit.OldNode, edit.NewNode)) { AddAroundActiveStatementRudeDiagnostic(diagnostics, edit.OldNode, edit.NewNode, newStatementSpan); } } } private static bool AreExceptionClausesEquivalent(SyntaxNode oldNode, SyntaxNode newNode) { switch (oldNode.Kind()) { case SyntaxKind.TryStatement: var oldTryStatement = (TryStatementSyntax)oldNode; var newTryStatement = (TryStatementSyntax)newNode; return SyntaxFactory.AreEquivalent(oldTryStatement.Finally, newTryStatement.Finally) && SyntaxFactory.AreEquivalent(oldTryStatement.Catches, newTryStatement.Catches); case SyntaxKind.CatchClause: case SyntaxKind.FinallyClause: return SyntaxFactory.AreEquivalent(oldNode, newNode); default: throw ExceptionUtilities.UnexpectedValue(oldNode.Kind()); } } /// <summary> /// An active statement (leaf or not) inside a "catch" makes the catch block read-only. /// An active statement (leaf or not) inside a "finally" makes the whole try/catch/finally block read-only. /// An active statement (non leaf) inside a "try" makes the catch/finally block read-only. /// </summary> /// <remarks> /// Exception handling regions are only needed to be tracked if they contain user code. /// <see cref="UsingStatementSyntax"/> and using <see cref="LocalDeclarationStatementSyntax"/> generate finally blocks, /// but they do not contain non-hidden sequence points. /// </remarks> /// <param name="node">An exception handling ancestor of an active statement node.</param> /// <param name="coversAllChildren"> /// True if all child nodes of the <paramref name="node"/> are contained in the exception region represented by the <paramref name="node"/>. /// </param> protected override TextSpan GetExceptionHandlingRegion(SyntaxNode node, out bool coversAllChildren) { TryStatementSyntax tryStatement; switch (node.Kind()) { case SyntaxKind.TryStatement: tryStatement = (TryStatementSyntax)node; coversAllChildren = false; if (tryStatement.Catches.Count == 0) { RoslynDebug.Assert(tryStatement.Finally != null); return tryStatement.Finally.Span; } return TextSpan.FromBounds( tryStatement.Catches.First().SpanStart, (tryStatement.Finally != null) ? tryStatement.Finally.Span.End : tryStatement.Catches.Last().Span.End); case SyntaxKind.CatchClause: coversAllChildren = true; return node.Span; case SyntaxKind.FinallyClause: coversAllChildren = true; tryStatement = (TryStatementSyntax)node.Parent!; return tryStatement.Span; default: throw ExceptionUtilities.UnexpectedValue(node.Kind()); } } #endregion #region State Machines internal override bool IsStateMachineMethod(SyntaxNode declaration) => SyntaxUtilities.IsAsyncDeclaration(declaration) || SyntaxUtilities.GetSuspensionPoints(declaration).Any(); protected override void GetStateMachineInfo(SyntaxNode body, out ImmutableArray<SyntaxNode> suspensionPoints, out StateMachineKinds kinds) { suspensionPoints = SyntaxUtilities.GetSuspensionPoints(body).ToImmutableArray(); kinds = StateMachineKinds.None; if (suspensionPoints.Any(n => n.IsKind(SyntaxKind.YieldBreakStatement) || n.IsKind(SyntaxKind.YieldReturnStatement))) { kinds |= StateMachineKinds.Iterator; } if (SyntaxUtilities.IsAsyncDeclaration(body.Parent)) { kinds |= StateMachineKinds.Async; } } internal override void ReportStateMachineSuspensionPointRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldNode, SyntaxNode newNode) { // TODO: changes around suspension points (foreach, lock, using, etc.) if (newNode.IsKind(SyntaxKind.AwaitExpression)) { var oldContainingStatementPart = FindContainingStatementPart(oldNode); var newContainingStatementPart = FindContainingStatementPart(newNode); // If the old statement has spilled state and the new doesn't the edit is ok. We'll just not use the spilled state. if (!SyntaxFactory.AreEquivalent(oldContainingStatementPart, newContainingStatementPart) && !HasNoSpilledState(newNode, newContainingStatementPart)) { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.AwaitStatementUpdate, newContainingStatementPart.Span)); } } } internal override void ReportStateMachineSuspensionPointDeletedRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode deletedSuspensionPoint) { // Handle deletion of await keyword from await foreach statement. if (deletedSuspensionPoint is CommonForEachStatementSyntax deletedForeachStatement && match.Matches.TryGetValue(deletedSuspensionPoint, out var newForEachStatement) && newForEachStatement is CommonForEachStatementSyntax && deletedForeachStatement.AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingFromAsynchronousToSynchronous, GetDiagnosticSpan(newForEachStatement, EditKind.Update), newForEachStatement, new[] { GetDisplayName(newForEachStatement, EditKind.Update) })); return; } // Handle deletion of await keyword from await using declaration. if (deletedSuspensionPoint.IsKind(SyntaxKind.VariableDeclarator) && match.Matches.TryGetValue(deletedSuspensionPoint.Parent!.Parent!, out var newLocalDeclaration) && !((LocalDeclarationStatementSyntax)newLocalDeclaration).AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingFromAsynchronousToSynchronous, GetDiagnosticSpan(newLocalDeclaration, EditKind.Update), newLocalDeclaration, new[] { GetDisplayName(newLocalDeclaration, EditKind.Update) })); return; } base.ReportStateMachineSuspensionPointDeletedRudeEdit(diagnostics, match, deletedSuspensionPoint); } internal override void ReportStateMachineSuspensionPointInsertedRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode insertedSuspensionPoint, bool aroundActiveStatement) { // Handle addition of await keyword to foreach statement. if (insertedSuspensionPoint is CommonForEachStatementSyntax insertedForEachStatement && match.ReverseMatches.TryGetValue(insertedSuspensionPoint, out var oldNode) && oldNode is CommonForEachStatementSyntax oldForEachStatement && !oldForEachStatement.AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.Insert, insertedForEachStatement.AwaitKeyword.Span, insertedForEachStatement, new[] { insertedForEachStatement.AwaitKeyword.ToString() })); return; } // Handle addition of using keyword to using declaration. if (insertedSuspensionPoint.IsKind(SyntaxKind.VariableDeclarator) && match.ReverseMatches.TryGetValue(insertedSuspensionPoint.Parent!.Parent!, out var oldLocalDeclaration) && !((LocalDeclarationStatementSyntax)oldLocalDeclaration).AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword)) { var newLocalDeclaration = (LocalDeclarationStatementSyntax)insertedSuspensionPoint!.Parent!.Parent!; diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.Insert, newLocalDeclaration.AwaitKeyword.Span, newLocalDeclaration, new[] { newLocalDeclaration.AwaitKeyword.ToString() })); return; } base.ReportStateMachineSuspensionPointInsertedRudeEdit(diagnostics, match, insertedSuspensionPoint, aroundActiveStatement); } private static SyntaxNode FindContainingStatementPart(SyntaxNode node) { while (true) { if (node is StatementSyntax statement) { return statement; } RoslynDebug.Assert(node is object); RoslynDebug.Assert(node.Parent is object); switch (node.Parent.Kind()) { case SyntaxKind.ForStatement: case SyntaxKind.ForEachStatement: case SyntaxKind.IfStatement: case SyntaxKind.WhileStatement: case SyntaxKind.DoStatement: case SyntaxKind.SwitchStatement: case SyntaxKind.LockStatement: case SyntaxKind.UsingStatement: case SyntaxKind.ArrowExpressionClause: return node; } if (LambdaUtilities.IsLambdaBodyStatementOrExpression(node)) { return node; } node = node.Parent; } } private static bool HasNoSpilledState(SyntaxNode awaitExpression, SyntaxNode containingStatementPart) { Debug.Assert(awaitExpression.IsKind(SyntaxKind.AwaitExpression)); // There is nothing within the statement part surrounding the await expression. if (containingStatementPart == awaitExpression) { return true; } switch (containingStatementPart.Kind()) { case SyntaxKind.ExpressionStatement: case SyntaxKind.ReturnStatement: var expression = GetExpressionFromStatementPart(containingStatementPart); // await expr; // return await expr; if (expression == awaitExpression) { return true; } // identifier = await expr; // return identifier = await expr; return IsSimpleAwaitAssignment(expression, awaitExpression); case SyntaxKind.VariableDeclaration: // var idf = await expr in using, for, etc. // EqualsValueClause -> VariableDeclarator -> VariableDeclaration return awaitExpression.Parent!.Parent!.Parent == containingStatementPart; case SyntaxKind.LocalDeclarationStatement: // var idf = await expr; // EqualsValueClause -> VariableDeclarator -> VariableDeclaration -> LocalDeclarationStatement return awaitExpression.Parent!.Parent!.Parent!.Parent == containingStatementPart; } return IsSimpleAwaitAssignment(containingStatementPart, awaitExpression); } private static ExpressionSyntax GetExpressionFromStatementPart(SyntaxNode statement) { switch (statement.Kind()) { case SyntaxKind.ExpressionStatement: return ((ExpressionStatementSyntax)statement).Expression; case SyntaxKind.ReturnStatement: // Must have an expression since we are only inspecting at statements that contain an expression. return ((ReturnStatementSyntax)statement).Expression!; default: throw ExceptionUtilities.UnexpectedValue(statement.Kind()); } } private static bool IsSimpleAwaitAssignment(SyntaxNode node, SyntaxNode awaitExpression) { if (node.IsKind(SyntaxKind.SimpleAssignmentExpression, out AssignmentExpressionSyntax? assignment)) { return assignment.Left.IsKind(SyntaxKind.IdentifierName) && assignment.Right == awaitExpression; } return false; } #endregion #region Rude Edits around Active Statement internal override void ReportOtherRudeEditsAroundActiveStatement( ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode oldActiveStatement, SyntaxNode newActiveStatement, bool isNonLeaf) { ReportRudeEditsForSwitchWhenClauses(diagnostics, oldActiveStatement, newActiveStatement); ReportRudeEditsForAncestorsDeclaringInterStatementTemps(diagnostics, match, oldActiveStatement, newActiveStatement); ReportRudeEditsForCheckedStatements(diagnostics, oldActiveStatement, newActiveStatement, isNonLeaf); } /// <summary> /// Reports rude edits when an active statement is a when clause in a switch statement and any of the switch cases or the switch value changed. /// This is necessary since the switch emits long-lived synthesized variables to store results of pattern evaluations. /// These synthesized variables are mapped to the slots of the new methods via ordinals. The mapping preserves the values of these variables as long as /// exactly the same variables are emitted for the new switch as they were for the old one and their order didn't change either. /// This is guaranteed if none of the case clauses have changed. /// </summary> private void ReportRudeEditsForSwitchWhenClauses(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldActiveStatement, SyntaxNode newActiveStatement) { if (!oldActiveStatement.IsKind(SyntaxKind.WhenClause)) { return; } // switch expression does not have sequence points (active statements): if (!(oldActiveStatement.Parent!.Parent!.Parent is SwitchStatementSyntax oldSwitch)) { return; } // switch statement does not match switch expression, so it must be part of a switch statement as well. var newSwitch = (SwitchStatementSyntax)newActiveStatement.Parent!.Parent!.Parent!; // when clauses can only match other when clauses: Debug.Assert(newActiveStatement.IsKind(SyntaxKind.WhenClause)); if (!AreEquivalentIgnoringLambdaBodies(oldSwitch.Expression, newSwitch.Expression)) { AddRudeUpdateAroundActiveStatement(diagnostics, newSwitch); } if (!AreEquivalentSwitchStatementDecisionTrees(oldSwitch, newSwitch)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.UpdateAroundActiveStatement, GetDiagnosticSpan(newSwitch, EditKind.Update), newSwitch, new[] { CSharpFeaturesResources.switch_statement_case_clause })); } } private static bool AreEquivalentSwitchStatementDecisionTrees(SwitchStatementSyntax oldSwitch, SwitchStatementSyntax newSwitch) => oldSwitch.Sections.SequenceEqual(newSwitch.Sections, AreSwitchSectionsEquivalent); private static bool AreSwitchSectionsEquivalent(SwitchSectionSyntax oldSection, SwitchSectionSyntax newSection) => oldSection.Labels.SequenceEqual(newSection.Labels, AreLabelsEquivalent); private static bool AreLabelsEquivalent(SwitchLabelSyntax oldLabel, SwitchLabelSyntax newLabel) { if (oldLabel.IsKind(SyntaxKind.CasePatternSwitchLabel, out CasePatternSwitchLabelSyntax? oldCasePatternLabel) && newLabel.IsKind(SyntaxKind.CasePatternSwitchLabel, out CasePatternSwitchLabelSyntax? newCasePatternLabel)) { // ignore the actual when expressions: return SyntaxFactory.AreEquivalent(oldCasePatternLabel.Pattern, newCasePatternLabel.Pattern) && (oldCasePatternLabel.WhenClause != null) == (newCasePatternLabel.WhenClause != null); } else { return SyntaxFactory.AreEquivalent(oldLabel, newLabel); } } private void ReportRudeEditsForCheckedStatements( ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldActiveStatement, SyntaxNode newActiveStatement, bool isNonLeaf) { // checked context can't be changed around non-leaf active statement: if (!isNonLeaf) { return; } // Changing checked context around an internal active statement may change the instructions // executed after method calls in the active statement but before the next sequence point. // Since the debugger remaps the IP at the first sequence point following a call instruction // allowing overflow context to be changed may lead to execution of code with old semantics. var oldCheckedStatement = TryGetCheckedStatementAncestor(oldActiveStatement); var newCheckedStatement = TryGetCheckedStatementAncestor(newActiveStatement); bool isRude; if (oldCheckedStatement == null || newCheckedStatement == null) { isRude = oldCheckedStatement != newCheckedStatement; } else { isRude = oldCheckedStatement.Kind() != newCheckedStatement.Kind(); } if (isRude) { AddAroundActiveStatementRudeDiagnostic(diagnostics, oldCheckedStatement, newCheckedStatement, newActiveStatement.Span); } } private static CheckedStatementSyntax? TryGetCheckedStatementAncestor(SyntaxNode? node) { // Ignoring lambda boundaries since checked context flows through. while (node != null) { switch (node.Kind()) { case SyntaxKind.CheckedStatement: case SyntaxKind.UncheckedStatement: return (CheckedStatementSyntax)node; } node = node.Parent; } return null; } private void ReportRudeEditsForAncestorsDeclaringInterStatementTemps( ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode oldActiveStatement, SyntaxNode newActiveStatement) { // Rude Edits for fixed/using/lock/foreach statements that are added/updated around an active statement. // Although such changes are technically possible, they might lead to confusion since // the temporary variables these statements generate won't be properly initialized. // // We use a simple algorithm to match each new node with its old counterpart. // If all nodes match this algorithm is linear, otherwise it's quadratic. // // Unlike exception regions matching where we use LCS, we allow reordering of the statements. ReportUnmatchedStatements<LockStatementSyntax>(diagnostics, match, n => n.IsKind(SyntaxKind.LockStatement), oldActiveStatement, newActiveStatement, areEquivalent: AreEquivalentActiveStatements, areSimilar: null); ReportUnmatchedStatements<FixedStatementSyntax>(diagnostics, match, n => n.IsKind(SyntaxKind.FixedStatement), oldActiveStatement, newActiveStatement, areEquivalent: AreEquivalentActiveStatements, areSimilar: (n1, n2) => DeclareSameIdentifiers(n1.Declaration.Variables, n2.Declaration.Variables)); // Using statements with declaration do not introduce compiler generated temporary. ReportUnmatchedStatements<UsingStatementSyntax>( diagnostics, match, n => n.IsKind(SyntaxKind.UsingStatement, out UsingStatementSyntax? usingStatement) && usingStatement.Declaration is null, oldActiveStatement, newActiveStatement, areEquivalent: AreEquivalentActiveStatements, areSimilar: null); ReportUnmatchedStatements<CommonForEachStatementSyntax>( diagnostics, match, n => n.IsKind(SyntaxKind.ForEachStatement) || n.IsKind(SyntaxKind.ForEachVariableStatement), oldActiveStatement, newActiveStatement, areEquivalent: AreEquivalentActiveStatements, areSimilar: AreSimilarActiveStatements); } private static bool DeclareSameIdentifiers(SeparatedSyntaxList<VariableDeclaratorSyntax> oldVariables, SeparatedSyntaxList<VariableDeclaratorSyntax> newVariables) => DeclareSameIdentifiers(oldVariables.Select(v => v.Identifier).ToArray(), newVariables.Select(v => v.Identifier).ToArray()); private static bool DeclareSameIdentifiers(SyntaxToken[] oldVariables, SyntaxToken[] newVariables) { if (oldVariables.Length != newVariables.Length) { return false; } for (var i = 0; i < oldVariables.Length; i++) { if (!SyntaxFactory.AreEquivalent(oldVariables[i], newVariables[i])) { return false; } } return true; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Differencing; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue { internal sealed class CSharpEditAndContinueAnalyzer : AbstractEditAndContinueAnalyzer { [ExportLanguageServiceFactory(typeof(IEditAndContinueAnalyzer), LanguageNames.CSharp), Shared] internal sealed class Factory : ILanguageServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public Factory() { } public ILanguageService CreateLanguageService(HostLanguageServices languageServices) { return new CSharpEditAndContinueAnalyzer(testFaultInjector: null); } } // Public for testing purposes public CSharpEditAndContinueAnalyzer(Action<SyntaxNode>? testFaultInjector = null) : base(testFaultInjector) { } #region Syntax Analysis private enum BlockPart { OpenBrace = DefaultStatementPart, CloseBrace = 1, } private enum ForEachPart { ForEach = DefaultStatementPart, VariableDeclaration = 1, In = 2, Expression = 3, } private enum SwitchExpressionPart { WholeExpression = DefaultStatementPart, // An active statement that covers IL generated for the decision tree: // <governing-expression> [|switch { <arm>, ..., <arm> }|] // This active statement is never a leaf active statement (does not correspond to a breakpoint span). SwitchBody = 1, } /// <returns> /// <see cref="BaseMethodDeclarationSyntax"/> for methods, operators, constructors, destructors and accessors. /// <see cref="VariableDeclaratorSyntax"/> for field initializers. /// <see cref="PropertyDeclarationSyntax"/> for property initializers and expression bodies. /// <see cref="IndexerDeclarationSyntax"/> for indexer expression bodies. /// <see cref="ArrowExpressionClauseSyntax"/> for getter of an expression-bodied property/indexer. /// </returns> internal override bool TryFindMemberDeclaration(SyntaxNode? root, SyntaxNode node, out OneOrMany<SyntaxNode> declarations) { var current = node; while (current != null && current != root) { switch (current.Kind()) { case SyntaxKind.MethodDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: declarations = new(current); return true; case SyntaxKind.PropertyDeclaration: // int P { get; } = [|initializer|]; RoslynDebug.Assert(((PropertyDeclarationSyntax)current).Initializer != null); declarations = new(current); return true; case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: // Active statements encompassing modifiers or type correspond to the first initialized field. // [|public static int F = 1|], G = 2; declarations = new(((BaseFieldDeclarationSyntax)current).Declaration.Variables.First()); return true; case SyntaxKind.VariableDeclarator: // public static int F = 1, [|G = 2|]; RoslynDebug.Assert(current.Parent.IsKind(SyntaxKind.VariableDeclaration)); switch (current.Parent.Parent!.Kind()) { case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: declarations = new(current); return true; } current = current.Parent; break; case SyntaxKind.ArrowExpressionClause: // represents getter symbol declaration node of a property/indexer with expression body if (current.Parent.IsKind(SyntaxKind.PropertyDeclaration, SyntaxKind.IndexerDeclaration)) { declarations = new(current); return true; } break; } current = current.Parent; } declarations = default; return false; } /// <returns> /// Given a node representing a declaration or a top-level match node returns: /// - <see cref="BlockSyntax"/> for method-like member declarations with block bodies (methods, operators, constructors, destructors, accessors). /// - <see cref="ExpressionSyntax"/> for variable declarators of fields, properties with an initializer expression, or /// for method-like member declarations with expression bodies (methods, properties, indexers, operators) /// - <see cref="CompilationUnitSyntax"/> for top level statements /// /// A null reference otherwise. /// </returns> internal override SyntaxNode? TryGetDeclarationBody(SyntaxNode node) { if (node.IsKind(SyntaxKind.VariableDeclarator, out VariableDeclaratorSyntax? variableDeclarator)) { return variableDeclarator.Initializer?.Value; } if (node is CompilationUnitSyntax unit && unit.ContainsTopLevelStatements()) { // For top level statements, where there is no syntax node to represent the entire body of the synthesized // main method we just use the compilation unit itself return node; } return SyntaxUtilities.TryGetMethodDeclarationBody(node); } internal override bool IsDeclarationWithSharedBody(SyntaxNode declaration) => false; protected override ImmutableArray<ISymbol> GetCapturedVariables(SemanticModel model, SyntaxNode memberBody) { if (memberBody is CompilationUnitSyntax unit && unit.ContainsTopLevelStatements()) { return model.AnalyzeDataFlow(((GlobalStatementSyntax)unit.Members[0]).Statement, unit.Members.OfType<GlobalStatementSyntax>().Last().Statement)!.Captured; } Debug.Assert(memberBody.IsKind(SyntaxKind.Block) || memberBody is ExpressionSyntax); return model.AnalyzeDataFlow(memberBody).Captured; } protected override bool AreHandledEventsEqual(IMethodSymbol oldMethod, IMethodSymbol newMethod) => true; internal override bool HasParameterClosureScope(ISymbol member) { // in instance constructor parameters are lifted to a closure different from method body return (member as IMethodSymbol)?.MethodKind == MethodKind.Constructor; } protected override IEnumerable<SyntaxNode> GetVariableUseSites(IEnumerable<SyntaxNode> roots, ISymbol localOrParameter, SemanticModel model, CancellationToken cancellationToken) { Debug.Assert(localOrParameter is IParameterSymbol || localOrParameter is ILocalSymbol || localOrParameter is IRangeVariableSymbol); // not supported (it's non trivial to find all places where "this" is used): Debug.Assert(!localOrParameter.IsThisParameter()); return from root in roots from node in root.DescendantNodesAndSelf() where node.IsKind(SyntaxKind.IdentifierName) let nameSyntax = (IdentifierNameSyntax)node where (string?)nameSyntax.Identifier.Value == localOrParameter.Name && (model.GetSymbolInfo(nameSyntax, cancellationToken).Symbol?.Equals(localOrParameter) ?? false) select node; } /// <returns> /// If <paramref name="node"/> is a method, accessor, operator, destructor, or constructor without an initializer, /// tokens of its block body, or tokens of the expression body. /// /// If <paramref name="node"/> is an indexer declaration the tokens of its expression body. /// /// If <paramref name="node"/> is a property declaration the tokens of its expression body or initializer. /// /// If <paramref name="node"/> is a constructor with an initializer, /// tokens of the initializer concatenated with tokens of the constructor body. /// /// If <paramref name="node"/> is a variable declarator of a field with an initializer, /// subset of the tokens of the field declaration depending on which variable declarator it is. /// /// Null reference otherwise. /// </returns> internal override IEnumerable<SyntaxToken>? TryGetActiveTokens(SyntaxNode node) { if (node.IsKind(SyntaxKind.VariableDeclarator)) { // TODO: The logic is similar to BreakpointSpans.TryCreateSpanForVariableDeclaration. Can we abstract it? var declarator = node; var fieldDeclaration = (BaseFieldDeclarationSyntax)declarator.Parent!.Parent!; var variableDeclaration = fieldDeclaration.Declaration; if (fieldDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword)) { return null; } if (variableDeclaration.Variables.Count == 1) { if (variableDeclaration.Variables[0].Initializer == null) { return null; } return fieldDeclaration.Modifiers.Concat(variableDeclaration.DescendantTokens()).Concat(fieldDeclaration.SemicolonToken); } if (declarator == variableDeclaration.Variables[0]) { return fieldDeclaration.Modifiers.Concat(variableDeclaration.Type.DescendantTokens()).Concat(node.DescendantTokens()); } return declarator.DescendantTokens(); } if (node is PropertyDeclarationSyntax { ExpressionBody: var propertyExpressionBody and not null }) { return propertyExpressionBody.Expression.DescendantTokens(); } if (node is IndexerDeclarationSyntax { ExpressionBody: var indexerExpressionBody and not null }) { return indexerExpressionBody.Expression.DescendantTokens(); } var bodyTokens = SyntaxUtilities.TryGetMethodDeclarationBody(node)?.DescendantTokens(); if (node.IsKind(SyntaxKind.ConstructorDeclaration, out ConstructorDeclarationSyntax? ctor)) { if (ctor.Initializer != null) { bodyTokens = ctor.Initializer.DescendantTokens().Concat(bodyTokens ?? Enumerable.Empty<SyntaxToken>()); } } return bodyTokens; } internal override (TextSpan envelope, TextSpan hole) GetActiveSpanEnvelope(SyntaxNode declaration) => (BreakpointSpans.GetEnvelope(declaration), default); protected override SyntaxNode GetEncompassingAncestorImpl(SyntaxNode bodyOrMatchRoot) { // Constructor may contain active nodes outside of its body (constructor initializer), // but within the body of the member declaration (the parent). if (bodyOrMatchRoot.Parent.IsKind(SyntaxKind.ConstructorDeclaration)) { return bodyOrMatchRoot.Parent; } // Field initializer match root -- an active statement may include the modifiers // and type specification of the field declaration. if (bodyOrMatchRoot.IsKind(SyntaxKind.EqualsValueClause) && bodyOrMatchRoot.Parent.IsKind(SyntaxKind.VariableDeclarator) && bodyOrMatchRoot.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration)) { return bodyOrMatchRoot.Parent.Parent; } // Field initializer body -- an active statement may include the modifiers // and type specification of the field declaration. if (bodyOrMatchRoot.Parent.IsKind(SyntaxKind.EqualsValueClause) && bodyOrMatchRoot.Parent.Parent.IsKind(SyntaxKind.VariableDeclarator) && bodyOrMatchRoot.Parent.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration)) { return bodyOrMatchRoot.Parent.Parent.Parent; } // otherwise all active statements are covered by the body/match root itself: return bodyOrMatchRoot; } protected override SyntaxNode FindStatementAndPartner(SyntaxNode declarationBody, TextSpan span, SyntaxNode? partnerDeclarationBody, out SyntaxNode? partner, out int statementPart) { var position = span.Start; SyntaxUtilities.AssertIsBody(declarationBody, allowLambda: false); if (position < declarationBody.SpanStart) { // Only constructors and the field initializers may have an [|active statement|] starting outside of the <<body>>. // Constructor: [|public C()|] <<{ }>> // Constructor initializer: public C() : [|base(expr)|] <<{ }>> // Constructor initializer with lambda: public C() : base(() => { [|...|] }) <<{ }>> // Field initializers: [|public int a = <<expr>>|], [|b = <<expr>>|]; // No need to special case property initializers here, the active statement always spans the initializer expression. if (declarationBody.Parent.IsKind(SyntaxKind.ConstructorDeclaration)) { var constructor = (ConstructorDeclarationSyntax)declarationBody.Parent; var partnerConstructor = (ConstructorDeclarationSyntax?)partnerDeclarationBody?.Parent; if (constructor.Initializer == null || position < constructor.Initializer.ColonToken.SpanStart) { statementPart = DefaultStatementPart; partner = partnerConstructor; return constructor; } declarationBody = constructor.Initializer; partnerDeclarationBody = partnerConstructor?.Initializer; } } if (!declarationBody.FullSpan.Contains(position)) { // invalid position, let's find a labeled node that encompasses the body: position = declarationBody.SpanStart; } SyntaxNode node; if (partnerDeclarationBody != null) { SyntaxUtilities.FindLeafNodeAndPartner(declarationBody, position, partnerDeclarationBody, out node, out partner); } else { node = declarationBody.FindToken(position).Parent!; partner = null; } while (true) { var isBody = node == declarationBody || LambdaUtilities.IsLambdaBodyStatementOrExpression(node); if (isBody || SyntaxComparer.Statement.HasLabel(node)) { switch (node.Kind()) { case SyntaxKind.Block: statementPart = (int)GetStatementPart((BlockSyntax)node, position); return node; case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: Debug.Assert(!isBody); statementPart = (int)GetStatementPart((CommonForEachStatementSyntax)node, position); return node; case SyntaxKind.DoStatement: // The active statement of DoStatement node is the while condition, // which is lexically not the closest breakpoint span (the body is). // do { ... } [|while (condition);|] Debug.Assert(position == ((DoStatementSyntax)node).WhileKeyword.SpanStart); Debug.Assert(!isBody); goto default; case SyntaxKind.PropertyDeclaration: // The active span corresponding to a property declaration is the span corresponding to its initializer (if any), // not the span corresponding to the accessor. // int P { [|get;|] } = [|<initializer>|]; Debug.Assert(position == ((PropertyDeclarationSyntax)node).Initializer!.SpanStart); goto default; case SyntaxKind.VariableDeclaration: // VariableDeclaration ::= TypeSyntax CommaSeparatedList(VariableDeclarator) // // The compiler places sequence points after each local variable initialization. // The TypeSyntax is considered to be part of the first sequence span. Debug.Assert(!isBody); node = ((VariableDeclarationSyntax)node).Variables.First(); if (partner != null) { partner = ((VariableDeclarationSyntax)partner).Variables.First(); } statementPart = DefaultStatementPart; return node; case SyntaxKind.SwitchExpression: // An active statement that covers IL generated for the decision tree: // <governing-expression> [|switch { <arm>, ..., <arm> }|] // This active statement is never a leaf active statement (does not correspond to a breakpoint span). var switchExpression = (SwitchExpressionSyntax)node; if (position == switchExpression.SwitchKeyword.SpanStart) { Debug.Assert(span.End == switchExpression.CloseBraceToken.Span.End); statementPart = (int)SwitchExpressionPart.SwitchBody; return node; } // The switch expression itself can be (a part of) an active statement associated with the containing node // For example, when it is used as a switch arm expression like so: // <expr> switch { <pattern> [|when <expr> switch { ... }|] ... } Debug.Assert(position == switchExpression.Span.Start); if (isBody) { goto default; } // ascend to parent node: break; case SyntaxKind.SwitchExpressionArm: // An active statement may occur in the when clause and in the arm expression: // <constant-pattern> [|when <condition>|] => [|<expression>|] // The former is covered by when-clause node - it's a labeled node. // The latter isn't enclosed in a distinct labeled syntax node and thus needs to be covered // by the arm node itself. Debug.Assert(position == ((SwitchExpressionArmSyntax)node).Expression.SpanStart); Debug.Assert(!isBody); goto default; default: statementPart = DefaultStatementPart; return node; } } node = node.Parent!; if (partner != null) { partner = partner.Parent; } } } private static BlockPart GetStatementPart(BlockSyntax node, int position) => position < node.OpenBraceToken.Span.End ? BlockPart.OpenBrace : BlockPart.CloseBrace; private static TextSpan GetActiveSpan(BlockSyntax node, BlockPart part) => part switch { BlockPart.OpenBrace => node.OpenBraceToken.Span, BlockPart.CloseBrace => node.CloseBraceToken.Span, _ => throw ExceptionUtilities.UnexpectedValue(part), }; private static ForEachPart GetStatementPart(CommonForEachStatementSyntax node, int position) => position < node.OpenParenToken.SpanStart ? ForEachPart.ForEach : position < node.InKeyword.SpanStart ? ForEachPart.VariableDeclaration : position < node.Expression.SpanStart ? ForEachPart.In : ForEachPart.Expression; private static TextSpan GetActiveSpan(ForEachStatementSyntax node, ForEachPart part) => part switch { ForEachPart.ForEach => node.ForEachKeyword.Span, ForEachPart.VariableDeclaration => TextSpan.FromBounds(node.Type.SpanStart, node.Identifier.Span.End), ForEachPart.In => node.InKeyword.Span, ForEachPart.Expression => node.Expression.Span, _ => throw ExceptionUtilities.UnexpectedValue(part), }; private static TextSpan GetActiveSpan(ForEachVariableStatementSyntax node, ForEachPart part) => part switch { ForEachPart.ForEach => node.ForEachKeyword.Span, ForEachPart.VariableDeclaration => TextSpan.FromBounds(node.Variable.SpanStart, node.Variable.Span.End), ForEachPart.In => node.InKeyword.Span, ForEachPart.Expression => node.Expression.Span, _ => throw ExceptionUtilities.UnexpectedValue(part), }; private static TextSpan GetActiveSpan(SwitchExpressionSyntax node, SwitchExpressionPart part) => part switch { SwitchExpressionPart.WholeExpression => node.Span, SwitchExpressionPart.SwitchBody => TextSpan.FromBounds(node.SwitchKeyword.SpanStart, node.CloseBraceToken.Span.End), _ => throw ExceptionUtilities.UnexpectedValue(part), }; protected override bool AreEquivalent(SyntaxNode left, SyntaxNode right) => SyntaxFactory.AreEquivalent(left, right); private static bool AreEquivalentIgnoringLambdaBodies(SyntaxNode left, SyntaxNode right) { // usual case: if (SyntaxFactory.AreEquivalent(left, right)) { return true; } return LambdaUtilities.AreEquivalentIgnoringLambdaBodies(left, right); } internal override SyntaxNode FindDeclarationBodyPartner(SyntaxNode leftRoot, SyntaxNode rightRoot, SyntaxNode leftNode) => SyntaxUtilities.FindPartner(leftRoot, rightRoot, leftNode); internal override bool IsClosureScope(SyntaxNode node) => LambdaUtilities.IsClosureScope(node); protected override SyntaxNode? FindEnclosingLambdaBody(SyntaxNode? container, SyntaxNode node) { var root = GetEncompassingAncestor(container); var current = node; while (current != root && current != null) { if (LambdaUtilities.IsLambdaBodyStatementOrExpression(current, out var body)) { return body; } current = current.Parent; } return null; } protected override IEnumerable<SyntaxNode> GetLambdaBodyExpressionsAndStatements(SyntaxNode lambdaBody) => SpecializedCollections.SingletonEnumerable(lambdaBody); protected override SyntaxNode? TryGetPartnerLambdaBody(SyntaxNode oldBody, SyntaxNode newLambda) => LambdaUtilities.TryGetCorrespondingLambdaBody(oldBody, newLambda); protected override Match<SyntaxNode> ComputeTopLevelMatch(SyntaxNode oldCompilationUnit, SyntaxNode newCompilationUnit) => SyntaxComparer.TopLevel.ComputeMatch(oldCompilationUnit, newCompilationUnit); protected override Match<SyntaxNode> ComputeTopLevelDeclarationMatch(SyntaxNode oldDeclaration, SyntaxNode newDeclaration) { Contract.ThrowIfNull(oldDeclaration.Parent); Contract.ThrowIfNull(newDeclaration.Parent); var comparer = new SyntaxComparer(oldDeclaration.Parent, newDeclaration.Parent, new[] { oldDeclaration }, new[] { newDeclaration }, compareStatementSyntax: false); return comparer.ComputeMatch(oldDeclaration.Parent, newDeclaration.Parent); } protected override Match<SyntaxNode> ComputeBodyMatch(SyntaxNode oldBody, SyntaxNode newBody, IEnumerable<KeyValuePair<SyntaxNode, SyntaxNode>>? knownMatches) { SyntaxUtilities.AssertIsBody(oldBody, allowLambda: true); SyntaxUtilities.AssertIsBody(newBody, allowLambda: true); if (oldBody is ExpressionSyntax || newBody is ExpressionSyntax || (oldBody.Parent.IsKind(SyntaxKind.LocalFunctionStatement) && newBody.Parent.IsKind(SyntaxKind.LocalFunctionStatement))) { Debug.Assert(oldBody is ExpressionSyntax || oldBody is BlockSyntax); Debug.Assert(newBody is ExpressionSyntax || newBody is BlockSyntax); // The matching algorithm requires the roots to match each other. // Lambda bodies, field/property initializers, and method/property/indexer/operator expression-bodies may also be lambda expressions. // Say we have oldBody 'x => x' and newBody 'F(x => x + 1)', then // the algorithm would match 'x => x' to 'F(x => x + 1)' instead of // matching 'x => x' to 'x => x + 1'. // We use the parent node as a root: // - for field/property initializers the root is EqualsValueClause. // - for member expression-bodies the root is ArrowExpressionClauseSyntax. // - for block bodies the root is a method/operator/accessor declaration (only happens when matching expression body with a block body) // - for lambdas the root is a LambdaExpression. // - for query lambdas the root is the query clause containing the lambda (e.g. where). // - for local functions the root is LocalFunctionStatement. static SyntaxNode GetMatchingRoot(SyntaxNode body) { var parent = body.Parent!; // We could apply this change across all ArrowExpressionClause consistently not just for ones with LocalFunctionStatement parents // but it would require an essential refactoring. return parent.IsKind(SyntaxKind.ArrowExpressionClause) && parent.Parent.IsKind(SyntaxKind.LocalFunctionStatement) ? parent.Parent : parent; } var oldRoot = GetMatchingRoot(oldBody); var newRoot = GetMatchingRoot(newBody); return new SyntaxComparer(oldRoot, newRoot, GetChildNodes(oldRoot, oldBody), GetChildNodes(newRoot, newBody), compareStatementSyntax: true).ComputeMatch(oldRoot, newRoot, knownMatches); } if (oldBody.Parent.IsKind(SyntaxKind.ConstructorDeclaration)) { // We need to include constructor initializer in the match, since it may contain lambdas. // Use the constructor declaration as a root. RoslynDebug.Assert(oldBody.IsKind(SyntaxKind.Block)); RoslynDebug.Assert(newBody.IsKind(SyntaxKind.Block)); RoslynDebug.Assert(newBody.Parent.IsKind(SyntaxKind.ConstructorDeclaration)); RoslynDebug.Assert(newBody.Parent is object); return SyntaxComparer.Statement.ComputeMatch(oldBody.Parent, newBody.Parent, knownMatches); } return SyntaxComparer.Statement.ComputeMatch(oldBody, newBody, knownMatches); } private static IEnumerable<SyntaxNode> GetChildNodes(SyntaxNode root, SyntaxNode body) { if (root is LocalFunctionStatementSyntax localFunc) { // local functions have multiple children we need to process for matches, but we won't automatically // descend into them, assuming they're nested, so we override the default behaviour and return // multiple children foreach (var attributeList in localFunc.AttributeLists) { yield return attributeList; } yield return localFunc.ReturnType; if (localFunc.TypeParameterList is not null) { yield return localFunc.TypeParameterList; } yield return localFunc.ParameterList; if (localFunc.Body is not null) { yield return localFunc.Body; } else if (localFunc.ExpressionBody is not null) { // Skip the ArrowExpressionClause that is ExressionBody and just return the expression itself yield return localFunc.ExpressionBody.Expression; } } else { yield return body; } } internal override void ReportDeclarationInsertDeleteRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldNode, SyntaxNode newNode, ISymbol oldSymbol, ISymbol newSymbol, CancellationToken cancellationToken) { // Global statements have a declaring syntax reference to the compilation unit itself, which we can just ignore // for the purposes of declaration rude edits if (oldNode.IsKind(SyntaxKind.CompilationUnit) || newNode.IsKind(SyntaxKind.CompilationUnit)) { return; } // Compiler generated methods of records have a declaring syntax reference to the record declaration itself // but their explicitly implemented counterparts reference the actual member. Compiler generated properties // of records reference the parameter that names them. // // Since there is no useful "old" syntax node for these members, we can't compute declaration or body edits // using the standard tree comparison code. // // Based on this, we can detect a new explicit implementation of a record member by checking if the // declaration kind has changed. If it hasn't changed, then our standard code will handle it. if (oldNode.RawKind == newNode.RawKind) { base.ReportDeclarationInsertDeleteRudeEdits(diagnostics, oldNode, newNode, oldSymbol, newSymbol, cancellationToken); return; } // When explicitly implementing a property that is represented by a positional parameter // what looks like an edit could actually be a rude delete, or something else if (oldNode is ParameterSyntax && newNode is PropertyDeclarationSyntax property) { if (property.AccessorList!.Accessors.Count == 1) { // Explicitly implementing a property with only one accessor is a delete of the init accessor, so a rude edit. // Not implementing the get accessor would be a compile error diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ImplementRecordParameterAsReadOnly, GetDiagnosticSpan(newNode, EditKind.Delete), oldNode, new[] { property.Identifier.ToString() })); } else if (property.AccessorList.Accessors.Any(a => a.IsKind(SyntaxKind.SetAccessorDeclaration))) { // The compiler implements the properties with an init accessor so explicitly implementing // it with a set accessor is a rude accessor change edit diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ImplementRecordParameterWithSet, GetDiagnosticSpan(newNode, EditKind.Delete), oldNode, new[] { property.Identifier.ToString() })); } } else if (oldNode is RecordDeclarationSyntax && newNode is MethodDeclarationSyntax && !oldSymbol.GetParameters().Select(p => p.Name).SequenceEqual(newSymbol.GetParameters().Select(p => p.Name))) { // TODO: Remove this requirement with https://github.com/dotnet/roslyn/issues/52563 // Explicitly implemented methods must have parameter names that match the compiler generated versions // exactly otherwise symbol matching won't work for them. // We don't need to worry about parameter types, because if they were different then we wouldn't get here // as this wouldn't be the explicit implementation of a known method. // We don't need to worry about access modifiers because the symbol matching still works, and most of the // time changing access modifiers for these known methods is a compile error anyway. diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ExplicitRecordMethodParameterNamesMustMatch, GetDiagnosticSpan(newNode, EditKind.Update), oldNode, new[] { oldSymbol.ToDisplayString(SymbolDisplayFormats.NameFormat) })); } } protected override void ReportLocalFunctionsDeclarationRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> bodyMatch) { var bodyEditsForLambda = bodyMatch.GetTreeEdits(); var editMap = BuildEditMap(bodyEditsForLambda); foreach (var edit in bodyEditsForLambda.Edits) { if (HasParentEdit(editMap, edit)) { return; } var classifier = new EditClassifier(this, diagnostics, edit.OldNode, edit.NewNode, edit.Kind, bodyMatch); classifier.ClassifyEdit(); } } protected override bool TryMatchActiveStatement( SyntaxNode oldStatement, int statementPart, SyntaxNode oldBody, SyntaxNode newBody, [NotNullWhen(true)] out SyntaxNode? newStatement) { SyntaxUtilities.AssertIsBody(oldBody, allowLambda: true); SyntaxUtilities.AssertIsBody(newBody, allowLambda: true); switch (oldStatement.Kind()) { case SyntaxKind.ThisConstructorInitializer: case SyntaxKind.BaseConstructorInitializer: case SyntaxKind.ConstructorDeclaration: var newConstructor = (ConstructorDeclarationSyntax)(newBody.Parent.IsKind(SyntaxKind.ArrowExpressionClause) ? newBody.Parent.Parent : newBody.Parent)!; newStatement = (SyntaxNode?)newConstructor.Initializer ?? newConstructor; return true; default: // TODO: Consider mapping an expression body to an equivalent statement expression or return statement and vice versa. // It would benefit transformations of expression bodies to block bodies of lambdas, methods, operators and properties. // See https://github.com/dotnet/roslyn/issues/22696 // field initializer, lambda and query expressions: if (oldStatement == oldBody && !newBody.IsKind(SyntaxKind.Block)) { newStatement = newBody; return true; } newStatement = null; return false; } } #endregion #region Syntax and Semantic Utils protected override TextSpan GetGlobalStatementDiagnosticSpan(SyntaxNode node) { if (node is CompilationUnitSyntax unit) { // When deleting something from a compilation unit we just report diagnostics for the last global statement return unit.Members.OfType<GlobalStatementSyntax>().LastOrDefault()?.Span ?? default; } return GetDiagnosticSpan(node, EditKind.Delete); } protected override string LineDirectiveKeyword => "line"; protected override ushort LineDirectiveSyntaxKind => (ushort)SyntaxKind.LineDirectiveTrivia; protected override IEnumerable<SequenceEdit> GetSyntaxSequenceEdits(ImmutableArray<SyntaxNode> oldNodes, ImmutableArray<SyntaxNode> newNodes) => SyntaxComparer.GetSequenceEdits(oldNodes, newNodes); internal override SyntaxNode EmptyCompilationUnit => SyntaxFactory.CompilationUnit(); // there are no experimental features at this time. internal override bool ExperimentalFeaturesEnabled(SyntaxTree tree) => false; protected override bool StateMachineSuspensionPointKindEquals(SyntaxNode suspensionPoint1, SyntaxNode suspensionPoint2) => (suspensionPoint1 is CommonForEachStatementSyntax) ? suspensionPoint2 is CommonForEachStatementSyntax : suspensionPoint1.RawKind == suspensionPoint2.RawKind; protected override bool StatementLabelEquals(SyntaxNode node1, SyntaxNode node2) => SyntaxComparer.Statement.GetLabel(node1) == SyntaxComparer.Statement.GetLabel(node2); protected override bool TryGetEnclosingBreakpointSpan(SyntaxNode root, int position, out TextSpan span) => BreakpointSpans.TryGetClosestBreakpointSpan(root, position, out span); protected override bool TryGetActiveSpan(SyntaxNode node, int statementPart, int minLength, out TextSpan span) { switch (node.Kind()) { case SyntaxKind.Block: span = GetActiveSpan((BlockSyntax)node, (BlockPart)statementPart); return true; case SyntaxKind.ForEachStatement: span = GetActiveSpan((ForEachStatementSyntax)node, (ForEachPart)statementPart); return true; case SyntaxKind.ForEachVariableStatement: span = GetActiveSpan((ForEachVariableStatementSyntax)node, (ForEachPart)statementPart); return true; case SyntaxKind.DoStatement: // The active statement of DoStatement node is the while condition, // which is lexically not the closest breakpoint span (the body is). // do { ... } [|while (condition);|] Debug.Assert(statementPart == DefaultStatementPart); var doStatement = (DoStatementSyntax)node; return BreakpointSpans.TryGetClosestBreakpointSpan(node, doStatement.WhileKeyword.SpanStart, out span); case SyntaxKind.PropertyDeclaration: // The active span corresponding to a property declaration is the span corresponding to its initializer (if any), // not the span corresponding to the accessor. // int P { [|get;|] } = [|<initializer>|]; Debug.Assert(statementPart == DefaultStatementPart); var propertyDeclaration = (PropertyDeclarationSyntax)node; if (propertyDeclaration.Initializer != null && BreakpointSpans.TryGetClosestBreakpointSpan(node, propertyDeclaration.Initializer.SpanStart, out span)) { return true; } span = default; return false; case SyntaxKind.SwitchExpression: span = GetActiveSpan((SwitchExpressionSyntax)node, (SwitchExpressionPart)statementPart); return true; case SyntaxKind.SwitchExpressionArm: // An active statement may occur in the when clause and in the arm expression: // <constant-pattern> [|when <condition>|] => [|<expression>|] // The former is covered by when-clause node - it's a labeled node. // The latter isn't enclosed in a distinct labeled syntax node and thus needs to be covered // by the arm node itself. Debug.Assert(statementPart == DefaultStatementPart); span = ((SwitchExpressionArmSyntax)node).Expression.Span; return true; default: // make sure all nodes that use statement parts are handled above: Debug.Assert(statementPart == DefaultStatementPart); return BreakpointSpans.TryGetClosestBreakpointSpan(node, node.SpanStart, out span); } } protected override IEnumerable<(SyntaxNode statement, int statementPart)> EnumerateNearStatements(SyntaxNode statement) { var direction = +1; SyntaxNodeOrToken nodeOrToken = statement; var fieldOrPropertyModifiers = SyntaxUtilities.TryGetFieldOrPropertyModifiers(statement); while (true) { nodeOrToken = (direction < 0) ? nodeOrToken.GetPreviousSibling() : nodeOrToken.GetNextSibling(); if (nodeOrToken.RawKind == 0) { var parent = statement.Parent; if (parent == null) { yield break; } switch (parent.Kind()) { case SyntaxKind.Block: // The next sequence point hit after the last statement of a block is the closing brace: yield return (parent, (int)(direction > 0 ? BlockPart.CloseBrace : BlockPart.OpenBrace)); break; case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: // The next sequence point hit after the body is the in keyword: // [|foreach|] ([|variable-declaration|] [|in|] [|expression|]) [|<body>|] yield return (parent, (int)ForEachPart.In); break; } if (direction > 0) { nodeOrToken = statement; direction = -1; continue; } if (fieldOrPropertyModifiers.HasValue) { // We enumerated all members and none of them has an initializer. // We don't have any better place where to place the span than the initial field. // Consider: in non-partial classes we could find a single constructor. // Otherwise, it would be confusing to select one arbitrarily. yield return (statement, -1); } nodeOrToken = statement = parent; fieldOrPropertyModifiers = SyntaxUtilities.TryGetFieldOrPropertyModifiers(statement); direction = +1; yield return (nodeOrToken.AsNode()!, DefaultStatementPart); } else { var node = nodeOrToken.AsNode(); if (node == null) { continue; } if (fieldOrPropertyModifiers.HasValue) { var nodeModifiers = SyntaxUtilities.TryGetFieldOrPropertyModifiers(node); if (!nodeModifiers.HasValue || nodeModifiers.Value.Any(SyntaxKind.StaticKeyword) != fieldOrPropertyModifiers.Value.Any(SyntaxKind.StaticKeyword)) { continue; } } switch (node.Kind()) { case SyntaxKind.Block: yield return (node, (int)(direction > 0 ? BlockPart.OpenBrace : BlockPart.CloseBrace)); break; case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: yield return (node, (int)ForEachPart.ForEach); break; } yield return (node, DefaultStatementPart); } } } protected override bool AreEquivalentActiveStatements(SyntaxNode oldStatement, SyntaxNode newStatement, int statementPart) { if (oldStatement.Kind() != newStatement.Kind()) { return false; } switch (oldStatement.Kind()) { case SyntaxKind.Block: // closing brace of a using statement or a block that contains using local declarations: if (statementPart == (int)BlockPart.CloseBrace) { if (oldStatement.Parent.IsKind(SyntaxKind.UsingStatement, out UsingStatementSyntax? oldUsing)) { return newStatement.Parent.IsKind(SyntaxKind.UsingStatement, out UsingStatementSyntax? newUsing) && AreEquivalentActiveStatements(oldUsing, newUsing); } return HasEquivalentUsingDeclarations((BlockSyntax)oldStatement, (BlockSyntax)newStatement); } return true; case SyntaxKind.ConstructorDeclaration: // The call could only change if the base type of the containing class changed. return true; case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: // only check the expression, edits in the body and the variable declaration are allowed: return AreEquivalentActiveStatements((CommonForEachStatementSyntax)oldStatement, (CommonForEachStatementSyntax)newStatement); case SyntaxKind.IfStatement: // only check the condition, edits in the body are allowed: return AreEquivalentActiveStatements((IfStatementSyntax)oldStatement, (IfStatementSyntax)newStatement); case SyntaxKind.WhileStatement: // only check the condition, edits in the body are allowed: return AreEquivalentActiveStatements((WhileStatementSyntax)oldStatement, (WhileStatementSyntax)newStatement); case SyntaxKind.DoStatement: // only check the condition, edits in the body are allowed: return AreEquivalentActiveStatements((DoStatementSyntax)oldStatement, (DoStatementSyntax)newStatement); case SyntaxKind.SwitchStatement: return AreEquivalentActiveStatements((SwitchStatementSyntax)oldStatement, (SwitchStatementSyntax)newStatement); case SyntaxKind.LockStatement: return AreEquivalentActiveStatements((LockStatementSyntax)oldStatement, (LockStatementSyntax)newStatement); case SyntaxKind.UsingStatement: return AreEquivalentActiveStatements((UsingStatementSyntax)oldStatement, (UsingStatementSyntax)newStatement); // fixed and for statements don't need special handling since the active statement is a variable declaration default: return AreEquivalentIgnoringLambdaBodies(oldStatement, newStatement); } } private static bool HasEquivalentUsingDeclarations(BlockSyntax oldBlock, BlockSyntax newBlock) { var oldUsingDeclarations = oldBlock.Statements.Where(s => s is LocalDeclarationStatementSyntax l && l.UsingKeyword != default); var newUsingDeclarations = newBlock.Statements.Where(s => s is LocalDeclarationStatementSyntax l && l.UsingKeyword != default); return oldUsingDeclarations.SequenceEqual(newUsingDeclarations, AreEquivalentIgnoringLambdaBodies); } private static bool AreEquivalentActiveStatements(IfStatementSyntax oldNode, IfStatementSyntax newNode) { // only check the condition, edits in the body are allowed: return AreEquivalentIgnoringLambdaBodies(oldNode.Condition, newNode.Condition); } private static bool AreEquivalentActiveStatements(WhileStatementSyntax oldNode, WhileStatementSyntax newNode) { // only check the condition, edits in the body are allowed: return AreEquivalentIgnoringLambdaBodies(oldNode.Condition, newNode.Condition); } private static bool AreEquivalentActiveStatements(DoStatementSyntax oldNode, DoStatementSyntax newNode) { // only check the condition, edits in the body are allowed: return AreEquivalentIgnoringLambdaBodies(oldNode.Condition, newNode.Condition); } private static bool AreEquivalentActiveStatements(SwitchStatementSyntax oldNode, SwitchStatementSyntax newNode) { // only check the expression, edits in the body are allowed, unless the switch expression contains patterns: if (!AreEquivalentIgnoringLambdaBodies(oldNode.Expression, newNode.Expression)) { return false; } // Check that switch statement decision tree has not changed. var hasDecitionTree = oldNode.Sections.Any(s => s.Labels.Any(l => l is CasePatternSwitchLabelSyntax)); return !hasDecitionTree || AreEquivalentSwitchStatementDecisionTrees(oldNode, newNode); } private static bool AreEquivalentActiveStatements(LockStatementSyntax oldNode, LockStatementSyntax newNode) { // only check the expression, edits in the body are allowed: return AreEquivalentIgnoringLambdaBodies(oldNode.Expression, newNode.Expression); } private static bool AreEquivalentActiveStatements(FixedStatementSyntax oldNode, FixedStatementSyntax newNode) => AreEquivalentIgnoringLambdaBodies(oldNode.Declaration, newNode.Declaration); private static bool AreEquivalentActiveStatements(UsingStatementSyntax oldNode, UsingStatementSyntax newNode) { // only check the expression/declaration, edits in the body are allowed: return AreEquivalentIgnoringLambdaBodies( (SyntaxNode?)oldNode.Declaration ?? oldNode.Expression!, (SyntaxNode?)newNode.Declaration ?? newNode.Expression!); } private static bool AreEquivalentActiveStatements(CommonForEachStatementSyntax oldNode, CommonForEachStatementSyntax newNode) { if (oldNode.Kind() != newNode.Kind() || !AreEquivalentIgnoringLambdaBodies(oldNode.Expression, newNode.Expression)) { return false; } switch (oldNode.Kind()) { case SyntaxKind.ForEachStatement: return AreEquivalentIgnoringLambdaBodies(((ForEachStatementSyntax)oldNode).Type, ((ForEachStatementSyntax)newNode).Type); case SyntaxKind.ForEachVariableStatement: return AreEquivalentIgnoringLambdaBodies(((ForEachVariableStatementSyntax)oldNode).Variable, ((ForEachVariableStatementSyntax)newNode).Variable); default: throw ExceptionUtilities.UnexpectedValue(oldNode.Kind()); } } private static bool AreSimilarActiveStatements(CommonForEachStatementSyntax oldNode, CommonForEachStatementSyntax newNode) { List<SyntaxToken>? oldTokens = null; List<SyntaxToken>? newTokens = null; SyntaxComparer.GetLocalNames(oldNode, ref oldTokens); SyntaxComparer.GetLocalNames(newNode, ref newTokens); // A valid foreach statement declares at least one variable. RoslynDebug.Assert(oldTokens != null); RoslynDebug.Assert(newTokens != null); return DeclareSameIdentifiers(oldTokens.ToArray(), newTokens.ToArray()); } internal override bool IsInterfaceDeclaration(SyntaxNode node) => node.IsKind(SyntaxKind.InterfaceDeclaration); internal override bool IsRecordDeclaration(SyntaxNode node) => node.IsKind(SyntaxKind.RecordDeclaration, SyntaxKind.RecordStructDeclaration); internal override SyntaxNode? TryGetContainingTypeDeclaration(SyntaxNode node) => node is CompilationUnitSyntax ? null : node.Parent!.FirstAncestorOrSelf<BaseTypeDeclarationSyntax>(); internal override bool HasBackingField(SyntaxNode propertyOrIndexerDeclaration) => propertyOrIndexerDeclaration.IsKind(SyntaxKind.PropertyDeclaration, out PropertyDeclarationSyntax? propertyDecl) && SyntaxUtilities.HasBackingField(propertyDecl); internal override bool TryGetAssociatedMemberDeclaration(SyntaxNode node, [NotNullWhen(true)] out SyntaxNode? declaration) { if (node.IsKind(SyntaxKind.Parameter, SyntaxKind.TypeParameter)) { Contract.ThrowIfFalse(node.IsParentKind(SyntaxKind.ParameterList, SyntaxKind.TypeParameterList, SyntaxKind.BracketedParameterList)); declaration = node.Parent!.Parent!; return true; } if (node.Parent.IsParentKind(SyntaxKind.PropertyDeclaration, SyntaxKind.IndexerDeclaration, SyntaxKind.EventDeclaration)) { declaration = node.Parent.Parent!; return true; } declaration = null; return false; } internal override bool IsDeclarationWithInitializer(SyntaxNode declaration) => declaration is VariableDeclaratorSyntax { Initializer: not null } || declaration is PropertyDeclarationSyntax { Initializer: not null }; internal override bool IsRecordPrimaryConstructorParameter(SyntaxNode declaration) => declaration is ParameterSyntax { Parent: ParameterListSyntax { Parent: RecordDeclarationSyntax } }; private static bool IsPropertyDeclarationMatchingPrimaryConstructorParameter(SyntaxNode declaration, INamedTypeSymbol newContainingType) { if (newContainingType.IsRecord && declaration is PropertyDeclarationSyntax { Identifier: { ValueText: var name } }) { // We need to use symbol information to find the primary constructor, because it could be in another file if the type is partial foreach (var reference in newContainingType.DeclaringSyntaxReferences) { // Since users can define as many constructors as they like, going back to syntax to find the parameter list // in the record declaration is the simplest way to check if there is a matching parameter if (reference.GetSyntax() is RecordDeclarationSyntax record && record.ParameterList is not null && record.ParameterList.Parameters.Any(p => p.Identifier.ValueText.Equals(name))) { return true; } } } return false; } internal override bool IsPropertyAccessorDeclarationMatchingPrimaryConstructorParameter(SyntaxNode declaration, INamedTypeSymbol newContainingType, out bool isFirstAccessor) { isFirstAccessor = false; if (declaration is AccessorDeclarationSyntax { Parent: AccessorListSyntax { Parent: PropertyDeclarationSyntax property } list } && IsPropertyDeclarationMatchingPrimaryConstructorParameter(property, newContainingType)) { isFirstAccessor = list.Accessors[0] == declaration; return true; } return false; } internal override bool IsConstructorWithMemberInitializers(SyntaxNode constructorDeclaration) => constructorDeclaration is ConstructorDeclarationSyntax ctor && (ctor.Initializer == null || ctor.Initializer.IsKind(SyntaxKind.BaseConstructorInitializer)); internal override bool IsPartial(INamedTypeSymbol type) { var syntaxRefs = type.DeclaringSyntaxReferences; return syntaxRefs.Length > 1 || ((BaseTypeDeclarationSyntax)syntaxRefs.Single().GetSyntax()).Modifiers.Any(SyntaxKind.PartialKeyword); } protected override SyntaxNode GetSymbolDeclarationSyntax(SyntaxReference reference, CancellationToken cancellationToken) => reference.GetSyntax(cancellationToken); protected override OneOrMany<(ISymbol? oldSymbol, ISymbol? newSymbol, EditKind editKind)> GetSymbolEdits( EditKind editKind, SyntaxNode? oldNode, SyntaxNode? newNode, SemanticModel? oldModel, SemanticModel newModel, IReadOnlyDictionary<SyntaxNode, EditKind> editMap, CancellationToken cancellationToken) { var oldSymbol = (oldNode != null) ? GetSymbolForEdit(oldNode, oldModel!, cancellationToken) : null; var newSymbol = (newNode != null) ? GetSymbolForEdit(newNode, newModel, cancellationToken) : null; switch (editKind) { case EditKind.Update: Contract.ThrowIfNull(oldNode); Contract.ThrowIfNull(newNode); Contract.ThrowIfNull(oldModel); // Certain updates of a property/indexer node affects its accessors. // Return all affected symbols for these updates. // 1) Old or new property/indexer has an expression body: // int this[...] => expr; // int this[...] { get => expr; } // int P => expr; // int P { get => expr; } = init if (oldNode is PropertyDeclarationSyntax { ExpressionBody: not null } or IndexerDeclarationSyntax { ExpressionBody: not null } || newNode is PropertyDeclarationSyntax { ExpressionBody: not null } or IndexerDeclarationSyntax { ExpressionBody: not null }) { Debug.Assert(oldSymbol is IPropertySymbol); Debug.Assert(newSymbol is IPropertySymbol); var oldGetterSymbol = ((IPropertySymbol)oldSymbol).GetMethod; var newGetterSymbol = ((IPropertySymbol)newSymbol).GetMethod; return OneOrMany.Create(ImmutableArray.Create((oldSymbol, newSymbol, editKind), (oldGetterSymbol, newGetterSymbol, editKind))); } // 2) Property/indexer declarations differ in readonly keyword. if (oldNode is PropertyDeclarationSyntax oldProperty && newNode is PropertyDeclarationSyntax newProperty && DiffersInReadOnlyModifier(oldProperty.Modifiers, newProperty.Modifiers) || oldNode is IndexerDeclarationSyntax oldIndexer && newNode is IndexerDeclarationSyntax newIndexer && DiffersInReadOnlyModifier(oldIndexer.Modifiers, newIndexer.Modifiers)) { Debug.Assert(oldSymbol is IPropertySymbol); Debug.Assert(newSymbol is IPropertySymbol); var oldPropertySymbol = (IPropertySymbol)oldSymbol; var newPropertySymbol = (IPropertySymbol)newSymbol; using var _ = ArrayBuilder<(ISymbol?, ISymbol?, EditKind)>.GetInstance(out var builder); builder.Add((oldPropertySymbol, newPropertySymbol, editKind)); if (oldPropertySymbol.GetMethod != null && newPropertySymbol.GetMethod != null && oldPropertySymbol.GetMethod.IsReadOnly != newPropertySymbol.GetMethod.IsReadOnly) { builder.Add((oldPropertySymbol.GetMethod, newPropertySymbol.GetMethod, editKind)); } if (oldPropertySymbol.SetMethod != null && newPropertySymbol.SetMethod != null && oldPropertySymbol.SetMethod.IsReadOnly != newPropertySymbol.SetMethod.IsReadOnly) { builder.Add((oldPropertySymbol.SetMethod, newPropertySymbol.SetMethod, editKind)); } return OneOrMany.Create(builder.ToImmutable()); } static bool DiffersInReadOnlyModifier(SyntaxTokenList oldModifiers, SyntaxTokenList newModifiers) => (oldModifiers.IndexOf(SyntaxKind.ReadOnlyKeyword) >= 0) != (newModifiers.IndexOf(SyntaxKind.ReadOnlyKeyword) >= 0); // Change in attributes or modifiers of a field affects all its variable declarations. if (oldNode is BaseFieldDeclarationSyntax oldField && newNode is BaseFieldDeclarationSyntax newField) { return GetFieldSymbolUpdates(oldField.Declaration.Variables, newField.Declaration.Variables); } // Chnage in type of a field affects all its variable declarations. if (oldNode is VariableDeclarationSyntax oldVariableDeclaration && newNode is VariableDeclarationSyntax newVariableDeclaration) { return GetFieldSymbolUpdates(oldVariableDeclaration.Variables, newVariableDeclaration.Variables); } OneOrMany<(ISymbol?, ISymbol?, EditKind)> GetFieldSymbolUpdates(SeparatedSyntaxList<VariableDeclaratorSyntax> oldVariables, SeparatedSyntaxList<VariableDeclaratorSyntax> newVariables) { if (oldVariables.Count == 1 && newVariables.Count == 1) { return OneOrMany.Create((oldModel.GetDeclaredSymbol(oldVariables[0], cancellationToken), newModel.GetDeclaredSymbol(newVariables[0], cancellationToken), EditKind.Update)); } var result = from oldVariable in oldVariables join newVariable in newVariables on oldVariable.Identifier.Text equals newVariable.Identifier.Text select (oldModel.GetDeclaredSymbol(oldVariable, cancellationToken), newModel.GetDeclaredSymbol(newVariable, cancellationToken), EditKind.Update); return OneOrMany.Create(result.ToImmutableArray()); } break; case EditKind.Delete: case EditKind.Insert: var node = oldNode ?? newNode; // If the entire block-bodied property/indexer is deleted/inserted (accessors and the list they are contained in), // ignore this edit. We will have a semantic edit for the property/indexer itself. if (node.IsKind(SyntaxKind.GetAccessorDeclaration)) { Debug.Assert(node.Parent.IsKind(SyntaxKind.AccessorList)); if (HasEdit(editMap, node.Parent, editKind) && !HasEdit(editMap, node.Parent.Parent, editKind)) { return OneOrMany<(ISymbol?, ISymbol?, EditKind)>.Empty; } } // Inserting/deleting an expression-bodied property/indexer affects two symbols: // the property/indexer itself and the getter. // int this[...] => expr; // int P => expr; if (node is PropertyDeclarationSyntax { ExpressionBody: not null } or IndexerDeclarationSyntax { ExpressionBody: not null }) { var oldGetterSymbol = ((IPropertySymbol?)oldSymbol)?.GetMethod; var newGetterSymbol = ((IPropertySymbol?)newSymbol)?.GetMethod; return OneOrMany.Create(ImmutableArray.Create((oldSymbol, newSymbol, editKind), (oldGetterSymbol, newGetterSymbol, editKind))); } // Inserting/deleting a type parameter constraint should result in an update of the corresponding type parameter symbol: if (node.IsKind(SyntaxKind.TypeParameterConstraintClause)) { return OneOrMany.Create(ImmutableArray.Create((oldSymbol, newSymbol, EditKind.Update))); } // Inserting/deleting a global statement should result in an update of the implicit main method: if (node.IsKind(SyntaxKind.GlobalStatement)) { return OneOrMany.Create(ImmutableArray.Create((oldSymbol, newSymbol, EditKind.Update))); } break; } return (editKind == EditKind.Delete ? oldSymbol : newSymbol) is null ? OneOrMany<(ISymbol?, ISymbol?, EditKind)>.Empty : new OneOrMany<(ISymbol?, ISymbol?, EditKind)>((oldSymbol, newSymbol, editKind)); } private static ISymbol? GetSymbolForEdit( SyntaxNode node, SemanticModel model, CancellationToken cancellationToken) { if (node.IsKind(SyntaxKind.UsingDirective, SyntaxKind.NamespaceDeclaration, SyntaxKind.FileScopedNamespaceDeclaration)) { return null; } if (node.IsKind(SyntaxKind.TypeParameterConstraintClause)) { var constraintClause = (TypeParameterConstraintClauseSyntax)node; var symbolInfo = model.GetSymbolInfo(constraintClause.Name, cancellationToken); return symbolInfo.Symbol; } // Top level code always lives in a synthesized Main method if (node.IsKind(SyntaxKind.GlobalStatement)) { return model.GetEnclosingSymbol(node.SpanStart, cancellationToken); } var symbol = model.GetDeclaredSymbol(node, cancellationToken); // TODO: this is incorrect (https://github.com/dotnet/roslyn/issues/54800) // Ignore partial method definition parts. // Partial method that does not have implementation part is not emitted to metadata. // Partial method without a definition part is a compilation error. if (symbol is IMethodSymbol { IsPartialDefinition: true }) { return null; } return symbol; } internal override bool ContainsLambda(SyntaxNode declaration) => declaration.DescendantNodes().Any(LambdaUtilities.IsLambda); internal override bool IsLambda(SyntaxNode node) => LambdaUtilities.IsLambda(node); internal override bool IsLocalFunction(SyntaxNode node) => node.IsKind(SyntaxKind.LocalFunctionStatement); internal override bool IsNestedFunction(SyntaxNode node) => node is AnonymousFunctionExpressionSyntax or LocalFunctionStatementSyntax; internal override bool TryGetLambdaBodies(SyntaxNode node, [NotNullWhen(true)] out SyntaxNode? body1, out SyntaxNode? body2) => LambdaUtilities.TryGetLambdaBodies(node, out body1, out body2); internal override SyntaxNode GetLambda(SyntaxNode lambdaBody) => LambdaUtilities.GetLambda(lambdaBody); internal override IMethodSymbol GetLambdaExpressionSymbol(SemanticModel model, SyntaxNode lambdaExpression, CancellationToken cancellationToken) { var bodyExpression = LambdaUtilities.GetNestedFunctionBody(lambdaExpression); return (IMethodSymbol)model.GetRequiredEnclosingSymbol(bodyExpression.SpanStart, cancellationToken); } internal override SyntaxNode? GetContainingQueryExpression(SyntaxNode node) => node.FirstAncestorOrSelf<QueryExpressionSyntax>(); internal override bool QueryClauseLambdasTypeEquivalent(SemanticModel oldModel, SyntaxNode oldNode, SemanticModel newModel, SyntaxNode newNode, CancellationToken cancellationToken) { switch (oldNode.Kind()) { case SyntaxKind.FromClause: case SyntaxKind.LetClause: case SyntaxKind.WhereClause: case SyntaxKind.OrderByClause: case SyntaxKind.JoinClause: var oldQueryClauseInfo = oldModel.GetQueryClauseInfo((QueryClauseSyntax)oldNode, cancellationToken); var newQueryClauseInfo = newModel.GetQueryClauseInfo((QueryClauseSyntax)newNode, cancellationToken); return MemberSignaturesEquivalent(oldQueryClauseInfo.CastInfo.Symbol, newQueryClauseInfo.CastInfo.Symbol) && MemberSignaturesEquivalent(oldQueryClauseInfo.OperationInfo.Symbol, newQueryClauseInfo.OperationInfo.Symbol); case SyntaxKind.AscendingOrdering: case SyntaxKind.DescendingOrdering: var oldOrderingInfo = oldModel.GetSymbolInfo(oldNode, cancellationToken); var newOrderingInfo = newModel.GetSymbolInfo(newNode, cancellationToken); return MemberSignaturesEquivalent(oldOrderingInfo.Symbol, newOrderingInfo.Symbol); case SyntaxKind.SelectClause: var oldSelectInfo = oldModel.GetSymbolInfo(oldNode, cancellationToken); var newSelectInfo = newModel.GetSymbolInfo(newNode, cancellationToken); // Changing reduced select clause to a non-reduced form or vice versa // adds/removes a call to Select method, which is a supported change. return oldSelectInfo.Symbol == null || newSelectInfo.Symbol == null || MemberSignaturesEquivalent(oldSelectInfo.Symbol, newSelectInfo.Symbol); case SyntaxKind.GroupClause: var oldGroupByInfo = oldModel.GetSymbolInfo(oldNode, cancellationToken); var newGroupByInfo = newModel.GetSymbolInfo(newNode, cancellationToken); return MemberSignaturesEquivalent(oldGroupByInfo.Symbol, newGroupByInfo.Symbol, GroupBySignatureComparer); default: return true; } } private static bool GroupBySignatureComparer(ImmutableArray<IParameterSymbol> oldParameters, ITypeSymbol oldReturnType, ImmutableArray<IParameterSymbol> newParameters, ITypeSymbol newReturnType) { // C# spec paragraph 7.16.2.6 "Groupby clauses": // // A query expression of the form // from x in e group v by k // is translated into // (e).GroupBy(x => k, x => v) // except when v is the identifier x, the translation is // (e).GroupBy(x => k) // // Possible signatures: // C<G<K, T>> GroupBy<K>(Func<T, K> keySelector); // C<G<K, E>> GroupBy<K, E>(Func<T, K> keySelector, Func<T, E> elementSelector); if (!TypesEquivalent(oldReturnType, newReturnType, exact: false)) { return false; } Debug.Assert(oldParameters.Length == 1 || oldParameters.Length == 2); Debug.Assert(newParameters.Length == 1 || newParameters.Length == 2); // The types of the lambdas have to be the same if present. // The element selector may be added/removed. if (!ParameterTypesEquivalent(oldParameters[0], newParameters[0], exact: false)) { return false; } if (oldParameters.Length == newParameters.Length && newParameters.Length == 2) { return ParameterTypesEquivalent(oldParameters[1], newParameters[1], exact: false); } return true; } #endregion #region Diagnostic Info protected override SymbolDisplayFormat ErrorDisplayFormat => SymbolDisplayFormat.CSharpErrorMessageFormat; protected override TextSpan? TryGetDiagnosticSpan(SyntaxNode node, EditKind editKind) => TryGetDiagnosticSpanImpl(node, editKind); internal static new TextSpan GetDiagnosticSpan(SyntaxNode node, EditKind editKind) => TryGetDiagnosticSpanImpl(node, editKind) ?? node.Span; private static TextSpan? TryGetDiagnosticSpanImpl(SyntaxNode node, EditKind editKind) => TryGetDiagnosticSpanImpl(node.Kind(), node, editKind); // internal for testing; kind is passed explicitly for testing as well internal static TextSpan? TryGetDiagnosticSpanImpl(SyntaxKind kind, SyntaxNode node, EditKind editKind) { switch (kind) { case SyntaxKind.CompilationUnit: return default(TextSpan); case SyntaxKind.GlobalStatement: return node.Span; case SyntaxKind.ExternAliasDirective: case SyntaxKind.UsingDirective: return node.Span; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: var ns = (BaseNamespaceDeclarationSyntax)node; return TextSpan.FromBounds(ns.NamespaceKeyword.SpanStart, ns.Name.Span.End); case SyntaxKind.ClassDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: var typeDeclaration = (TypeDeclarationSyntax)node; return GetDiagnosticSpan(typeDeclaration.Modifiers, typeDeclaration.Keyword, typeDeclaration.TypeParameterList ?? (SyntaxNodeOrToken)typeDeclaration.Identifier); case SyntaxKind.EnumDeclaration: var enumDeclaration = (EnumDeclarationSyntax)node; return GetDiagnosticSpan(enumDeclaration.Modifiers, enumDeclaration.EnumKeyword, enumDeclaration.Identifier); case SyntaxKind.DelegateDeclaration: var delegateDeclaration = (DelegateDeclarationSyntax)node; return GetDiagnosticSpan(delegateDeclaration.Modifiers, delegateDeclaration.DelegateKeyword, delegateDeclaration.ParameterList); case SyntaxKind.FieldDeclaration: var fieldDeclaration = (BaseFieldDeclarationSyntax)node; return GetDiagnosticSpan(fieldDeclaration.Modifiers, fieldDeclaration.Declaration, fieldDeclaration.Declaration); case SyntaxKind.EventFieldDeclaration: var eventFieldDeclaration = (EventFieldDeclarationSyntax)node; return GetDiagnosticSpan(eventFieldDeclaration.Modifiers, eventFieldDeclaration.EventKeyword, eventFieldDeclaration.Declaration); case SyntaxKind.VariableDeclaration: return TryGetDiagnosticSpanImpl(node.Parent!, editKind); case SyntaxKind.VariableDeclarator: return node.Span; case SyntaxKind.MethodDeclaration: var methodDeclaration = (MethodDeclarationSyntax)node; return GetDiagnosticSpan(methodDeclaration.Modifiers, methodDeclaration.ReturnType, methodDeclaration.ParameterList); case SyntaxKind.ConversionOperatorDeclaration: var conversionOperatorDeclaration = (ConversionOperatorDeclarationSyntax)node; return GetDiagnosticSpan(conversionOperatorDeclaration.Modifiers, conversionOperatorDeclaration.ImplicitOrExplicitKeyword, conversionOperatorDeclaration.ParameterList); case SyntaxKind.OperatorDeclaration: var operatorDeclaration = (OperatorDeclarationSyntax)node; return GetDiagnosticSpan(operatorDeclaration.Modifiers, operatorDeclaration.ReturnType, operatorDeclaration.ParameterList); case SyntaxKind.ConstructorDeclaration: var constructorDeclaration = (ConstructorDeclarationSyntax)node; return GetDiagnosticSpan(constructorDeclaration.Modifiers, constructorDeclaration.Identifier, constructorDeclaration.ParameterList); case SyntaxKind.DestructorDeclaration: var destructorDeclaration = (DestructorDeclarationSyntax)node; return GetDiagnosticSpan(destructorDeclaration.Modifiers, destructorDeclaration.TildeToken, destructorDeclaration.ParameterList); case SyntaxKind.PropertyDeclaration: var propertyDeclaration = (PropertyDeclarationSyntax)node; return GetDiagnosticSpan(propertyDeclaration.Modifiers, propertyDeclaration.Type, propertyDeclaration.Identifier); case SyntaxKind.IndexerDeclaration: var indexerDeclaration = (IndexerDeclarationSyntax)node; return GetDiagnosticSpan(indexerDeclaration.Modifiers, indexerDeclaration.Type, indexerDeclaration.ParameterList); case SyntaxKind.EventDeclaration: var eventDeclaration = (EventDeclarationSyntax)node; return GetDiagnosticSpan(eventDeclaration.Modifiers, eventDeclaration.EventKeyword, eventDeclaration.Identifier); case SyntaxKind.EnumMemberDeclaration: return node.Span; case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: case SyntaxKind.UnknownAccessorDeclaration: var accessorDeclaration = (AccessorDeclarationSyntax)node; return GetDiagnosticSpan(accessorDeclaration.Modifiers, accessorDeclaration.Keyword, accessorDeclaration.Keyword); case SyntaxKind.TypeParameterConstraintClause: var constraint = (TypeParameterConstraintClauseSyntax)node; return TextSpan.FromBounds(constraint.WhereKeyword.SpanStart, constraint.Constraints.Last().Span.End); case SyntaxKind.TypeParameter: var typeParameter = (TypeParameterSyntax)node; return typeParameter.Identifier.Span; case SyntaxKind.AccessorList: case SyntaxKind.TypeParameterList: case SyntaxKind.ParameterList: case SyntaxKind.BracketedParameterList: if (editKind == EditKind.Delete) { return TryGetDiagnosticSpanImpl(node.Parent!, editKind); } else { return node.Span; } case SyntaxKind.Parameter: var parameter = (ParameterSyntax)node; // Lambda parameters don't have types or modifiers, so the parameter is the only node var startNode = parameter.Type ?? (SyntaxNode)parameter; return GetDiagnosticSpan(parameter.Modifiers, startNode, parameter); case SyntaxKind.AttributeList: var attributeList = (AttributeListSyntax)node; return attributeList.Span; case SyntaxKind.Attribute: return node.Span; case SyntaxKind.ArrowExpressionClause: return TryGetDiagnosticSpanImpl(node.Parent!, editKind); // We only need a diagnostic span if reporting an error for a child statement. // The following statements may have child statements. case SyntaxKind.Block: return ((BlockSyntax)node).OpenBraceToken.Span; case SyntaxKind.UsingStatement: var usingStatement = (UsingStatementSyntax)node; return TextSpan.FromBounds(usingStatement.UsingKeyword.SpanStart, usingStatement.CloseParenToken.Span.End); case SyntaxKind.FixedStatement: var fixedStatement = (FixedStatementSyntax)node; return TextSpan.FromBounds(fixedStatement.FixedKeyword.SpanStart, fixedStatement.CloseParenToken.Span.End); case SyntaxKind.LockStatement: var lockStatement = (LockStatementSyntax)node; return TextSpan.FromBounds(lockStatement.LockKeyword.SpanStart, lockStatement.CloseParenToken.Span.End); case SyntaxKind.StackAllocArrayCreationExpression: return ((StackAllocArrayCreationExpressionSyntax)node).StackAllocKeyword.Span; case SyntaxKind.ImplicitStackAllocArrayCreationExpression: return ((ImplicitStackAllocArrayCreationExpressionSyntax)node).StackAllocKeyword.Span; case SyntaxKind.TryStatement: return ((TryStatementSyntax)node).TryKeyword.Span; case SyntaxKind.CatchClause: return ((CatchClauseSyntax)node).CatchKeyword.Span; case SyntaxKind.CatchDeclaration: case SyntaxKind.CatchFilterClause: return node.Span; case SyntaxKind.FinallyClause: return ((FinallyClauseSyntax)node).FinallyKeyword.Span; case SyntaxKind.IfStatement: var ifStatement = (IfStatementSyntax)node; return TextSpan.FromBounds(ifStatement.IfKeyword.SpanStart, ifStatement.CloseParenToken.Span.End); case SyntaxKind.ElseClause: return ((ElseClauseSyntax)node).ElseKeyword.Span; case SyntaxKind.SwitchStatement: var switchStatement = (SwitchStatementSyntax)node; return TextSpan.FromBounds(switchStatement.SwitchKeyword.SpanStart, (switchStatement.CloseParenToken != default) ? switchStatement.CloseParenToken.Span.End : switchStatement.Expression.Span.End); case SyntaxKind.SwitchSection: return ((SwitchSectionSyntax)node).Labels.Last().Span; case SyntaxKind.WhileStatement: var whileStatement = (WhileStatementSyntax)node; return TextSpan.FromBounds(whileStatement.WhileKeyword.SpanStart, whileStatement.CloseParenToken.Span.End); case SyntaxKind.DoStatement: return ((DoStatementSyntax)node).DoKeyword.Span; case SyntaxKind.ForStatement: var forStatement = (ForStatementSyntax)node; return TextSpan.FromBounds(forStatement.ForKeyword.SpanStart, forStatement.CloseParenToken.Span.End); case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: var commonForEachStatement = (CommonForEachStatementSyntax)node; return TextSpan.FromBounds( (commonForEachStatement.AwaitKeyword.Span.Length > 0) ? commonForEachStatement.AwaitKeyword.SpanStart : commonForEachStatement.ForEachKeyword.SpanStart, commonForEachStatement.CloseParenToken.Span.End); case SyntaxKind.LabeledStatement: return ((LabeledStatementSyntax)node).Identifier.Span; case SyntaxKind.CheckedStatement: case SyntaxKind.UncheckedStatement: return ((CheckedStatementSyntax)node).Keyword.Span; case SyntaxKind.UnsafeStatement: return ((UnsafeStatementSyntax)node).UnsafeKeyword.Span; case SyntaxKind.LocalFunctionStatement: var lfd = (LocalFunctionStatementSyntax)node; return lfd.Identifier.Span; case SyntaxKind.YieldBreakStatement: case SyntaxKind.YieldReturnStatement: case SyntaxKind.ReturnStatement: case SyntaxKind.ThrowStatement: case SyntaxKind.ExpressionStatement: case SyntaxKind.EmptyStatement: case SyntaxKind.GotoStatement: case SyntaxKind.GotoCaseStatement: case SyntaxKind.GotoDefaultStatement: case SyntaxKind.BreakStatement: case SyntaxKind.ContinueStatement: return node.Span; case SyntaxKind.LocalDeclarationStatement: var localDeclarationStatement = (LocalDeclarationStatementSyntax)node; return CombineSpans(localDeclarationStatement.AwaitKeyword.Span, localDeclarationStatement.UsingKeyword.Span, node.Span); case SyntaxKind.AwaitExpression: return ((AwaitExpressionSyntax)node).AwaitKeyword.Span; case SyntaxKind.AnonymousObjectCreationExpression: return ((AnonymousObjectCreationExpressionSyntax)node).NewKeyword.Span; case SyntaxKind.ParenthesizedLambdaExpression: return ((ParenthesizedLambdaExpressionSyntax)node).ParameterList.Span; case SyntaxKind.SimpleLambdaExpression: return ((SimpleLambdaExpressionSyntax)node).Parameter.Span; case SyntaxKind.AnonymousMethodExpression: return ((AnonymousMethodExpressionSyntax)node).DelegateKeyword.Span; case SyntaxKind.QueryExpression: return ((QueryExpressionSyntax)node).FromClause.FromKeyword.Span; case SyntaxKind.QueryBody: var queryBody = (QueryBodySyntax)node; return TryGetDiagnosticSpanImpl(queryBody.Clauses.FirstOrDefault() ?? queryBody.Parent!, editKind); case SyntaxKind.QueryContinuation: return ((QueryContinuationSyntax)node).IntoKeyword.Span; case SyntaxKind.FromClause: return ((FromClauseSyntax)node).FromKeyword.Span; case SyntaxKind.JoinClause: return ((JoinClauseSyntax)node).JoinKeyword.Span; case SyntaxKind.JoinIntoClause: return ((JoinIntoClauseSyntax)node).IntoKeyword.Span; case SyntaxKind.LetClause: return ((LetClauseSyntax)node).LetKeyword.Span; case SyntaxKind.WhereClause: return ((WhereClauseSyntax)node).WhereKeyword.Span; case SyntaxKind.OrderByClause: return ((OrderByClauseSyntax)node).OrderByKeyword.Span; case SyntaxKind.AscendingOrdering: case SyntaxKind.DescendingOrdering: return node.Span; case SyntaxKind.SelectClause: return ((SelectClauseSyntax)node).SelectKeyword.Span; case SyntaxKind.GroupClause: return ((GroupClauseSyntax)node).GroupKeyword.Span; case SyntaxKind.IsPatternExpression: case SyntaxKind.TupleType: case SyntaxKind.TupleExpression: case SyntaxKind.DeclarationExpression: case SyntaxKind.RefType: case SyntaxKind.RefExpression: case SyntaxKind.DeclarationPattern: case SyntaxKind.SimpleAssignmentExpression: case SyntaxKind.WhenClause: case SyntaxKind.SingleVariableDesignation: case SyntaxKind.CasePatternSwitchLabel: return node.Span; case SyntaxKind.SwitchExpression: return ((SwitchExpressionSyntax)node).SwitchKeyword.Span; case SyntaxKind.SwitchExpressionArm: return ((SwitchExpressionArmSyntax)node).EqualsGreaterThanToken.Span; default: return null; } } private static TextSpan GetDiagnosticSpan(SyntaxTokenList modifiers, SyntaxNodeOrToken start, SyntaxNodeOrToken end) => TextSpan.FromBounds((modifiers.Count != 0) ? modifiers.First().SpanStart : start.SpanStart, end.Span.End); private static TextSpan CombineSpans(TextSpan first, TextSpan second, TextSpan defaultSpan) => (first.Length > 0 && second.Length > 0) ? TextSpan.FromBounds(first.Start, second.End) : (first.Length > 0) ? first : (second.Length > 0) ? second : defaultSpan; internal override TextSpan GetLambdaParameterDiagnosticSpan(SyntaxNode lambda, int ordinal) { Debug.Assert(ordinal >= 0); switch (lambda.Kind()) { case SyntaxKind.ParenthesizedLambdaExpression: return ((ParenthesizedLambdaExpressionSyntax)lambda).ParameterList.Parameters[ordinal].Identifier.Span; case SyntaxKind.SimpleLambdaExpression: Debug.Assert(ordinal == 0); return ((SimpleLambdaExpressionSyntax)lambda).Parameter.Identifier.Span; case SyntaxKind.AnonymousMethodExpression: // since we are given a parameter ordinal there has to be a parameter list: return ((AnonymousMethodExpressionSyntax)lambda).ParameterList!.Parameters[ordinal].Identifier.Span; default: return lambda.Span; } } internal override string GetDisplayName(INamedTypeSymbol symbol) => symbol.TypeKind switch { TypeKind.Struct => symbol.IsRecord ? CSharpFeaturesResources.record_struct : CSharpFeaturesResources.struct_, TypeKind.Class => symbol.IsRecord ? CSharpFeaturesResources.record_ : FeaturesResources.class_, _ => base.GetDisplayName(symbol) }; internal override string GetDisplayName(IPropertySymbol symbol) => symbol.IsIndexer ? CSharpFeaturesResources.indexer : base.GetDisplayName(symbol); internal override string GetDisplayName(IMethodSymbol symbol) => symbol.MethodKind switch { MethodKind.PropertyGet => symbol.AssociatedSymbol is IPropertySymbol { IsIndexer: true } ? CSharpFeaturesResources.indexer_getter : CSharpFeaturesResources.property_getter, MethodKind.PropertySet => symbol.AssociatedSymbol is IPropertySymbol { IsIndexer: true } ? CSharpFeaturesResources.indexer_setter : CSharpFeaturesResources.property_setter, MethodKind.StaticConstructor => FeaturesResources.static_constructor, MethodKind.Destructor => CSharpFeaturesResources.destructor, MethodKind.Conversion => CSharpFeaturesResources.conversion_operator, MethodKind.LocalFunction => FeaturesResources.local_function, _ => base.GetDisplayName(symbol) }; protected override string? TryGetDisplayName(SyntaxNode node, EditKind editKind) => TryGetDisplayNameImpl(node, editKind); internal static new string? GetDisplayName(SyntaxNode node, EditKind editKind) => TryGetDisplayNameImpl(node, editKind) ?? throw ExceptionUtilities.UnexpectedValue(node.Kind()); internal static string? TryGetDisplayNameImpl(SyntaxNode node, EditKind editKind) { switch (node.Kind()) { // top-level case SyntaxKind.CompilationUnit: case SyntaxKind.GlobalStatement: return CSharpFeaturesResources.global_statement; case SyntaxKind.ExternAliasDirective: return CSharpFeaturesResources.extern_alias; case SyntaxKind.UsingDirective: // Dev12 distinguishes using alias from using namespace and reports different errors for removing alias. // None of these changes are allowed anyways, so let's keep it simple. return CSharpFeaturesResources.using_directive; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: return FeaturesResources.namespace_; case SyntaxKind.ClassDeclaration: return FeaturesResources.class_; case SyntaxKind.StructDeclaration: return CSharpFeaturesResources.struct_; case SyntaxKind.InterfaceDeclaration: return FeaturesResources.interface_; case SyntaxKind.RecordDeclaration: return CSharpFeaturesResources.record_; case SyntaxKind.RecordStructDeclaration: return CSharpFeaturesResources.record_struct; case SyntaxKind.EnumDeclaration: return FeaturesResources.enum_; case SyntaxKind.DelegateDeclaration: return FeaturesResources.delegate_; case SyntaxKind.FieldDeclaration: var declaration = (FieldDeclarationSyntax)node; return declaration.Modifiers.Any(SyntaxKind.ConstKeyword) ? FeaturesResources.const_field : FeaturesResources.field; case SyntaxKind.EventFieldDeclaration: return CSharpFeaturesResources.event_field; case SyntaxKind.VariableDeclaration: case SyntaxKind.VariableDeclarator: return TryGetDisplayNameImpl(node.Parent!, editKind); case SyntaxKind.MethodDeclaration: return FeaturesResources.method; case SyntaxKind.ConversionOperatorDeclaration: return CSharpFeaturesResources.conversion_operator; case SyntaxKind.OperatorDeclaration: return FeaturesResources.operator_; case SyntaxKind.ConstructorDeclaration: var ctor = (ConstructorDeclarationSyntax)node; return ctor.Modifiers.Any(SyntaxKind.StaticKeyword) ? FeaturesResources.static_constructor : FeaturesResources.constructor; case SyntaxKind.DestructorDeclaration: return CSharpFeaturesResources.destructor; case SyntaxKind.PropertyDeclaration: return SyntaxUtilities.HasBackingField((PropertyDeclarationSyntax)node) ? FeaturesResources.auto_property : FeaturesResources.property_; case SyntaxKind.IndexerDeclaration: return CSharpFeaturesResources.indexer; case SyntaxKind.EventDeclaration: return FeaturesResources.event_; case SyntaxKind.EnumMemberDeclaration: return FeaturesResources.enum_value; case SyntaxKind.GetAccessorDeclaration: if (node.Parent!.Parent!.IsKind(SyntaxKind.PropertyDeclaration)) { return CSharpFeaturesResources.property_getter; } else { RoslynDebug.Assert(node.Parent.Parent.IsKind(SyntaxKind.IndexerDeclaration)); return CSharpFeaturesResources.indexer_getter; } case SyntaxKind.InitAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: if (node.Parent!.Parent!.IsKind(SyntaxKind.PropertyDeclaration)) { return CSharpFeaturesResources.property_setter; } else { RoslynDebug.Assert(node.Parent.Parent.IsKind(SyntaxKind.IndexerDeclaration)); return CSharpFeaturesResources.indexer_setter; } case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return FeaturesResources.event_accessor; case SyntaxKind.ArrowExpressionClause: return node.Parent!.Kind() switch { SyntaxKind.PropertyDeclaration => CSharpFeaturesResources.property_getter, SyntaxKind.IndexerDeclaration => CSharpFeaturesResources.indexer_getter, _ => null }; case SyntaxKind.TypeParameterConstraintClause: return FeaturesResources.type_constraint; case SyntaxKind.TypeParameterList: case SyntaxKind.TypeParameter: return FeaturesResources.type_parameter; case SyntaxKind.Parameter: return FeaturesResources.parameter; case SyntaxKind.AttributeList: return FeaturesResources.attribute; case SyntaxKind.Attribute: return FeaturesResources.attribute; case SyntaxKind.AttributeTargetSpecifier: return CSharpFeaturesResources.attribute_target; // statement: case SyntaxKind.TryStatement: return CSharpFeaturesResources.try_block; case SyntaxKind.CatchClause: case SyntaxKind.CatchDeclaration: return CSharpFeaturesResources.catch_clause; case SyntaxKind.CatchFilterClause: return CSharpFeaturesResources.filter_clause; case SyntaxKind.FinallyClause: return CSharpFeaturesResources.finally_clause; case SyntaxKind.FixedStatement: return CSharpFeaturesResources.fixed_statement; case SyntaxKind.UsingStatement: return CSharpFeaturesResources.using_statement; case SyntaxKind.LockStatement: return CSharpFeaturesResources.lock_statement; case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: return CSharpFeaturesResources.foreach_statement; case SyntaxKind.CheckedStatement: return CSharpFeaturesResources.checked_statement; case SyntaxKind.UncheckedStatement: return CSharpFeaturesResources.unchecked_statement; case SyntaxKind.YieldBreakStatement: return CSharpFeaturesResources.yield_break_statement; case SyntaxKind.YieldReturnStatement: return CSharpFeaturesResources.yield_return_statement; case SyntaxKind.AwaitExpression: return CSharpFeaturesResources.await_expression; case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: return CSharpFeaturesResources.lambda; case SyntaxKind.AnonymousMethodExpression: return CSharpFeaturesResources.anonymous_method; case SyntaxKind.FromClause: return CSharpFeaturesResources.from_clause; case SyntaxKind.JoinClause: case SyntaxKind.JoinIntoClause: return CSharpFeaturesResources.join_clause; case SyntaxKind.LetClause: return CSharpFeaturesResources.let_clause; case SyntaxKind.WhereClause: return CSharpFeaturesResources.where_clause; case SyntaxKind.OrderByClause: case SyntaxKind.AscendingOrdering: case SyntaxKind.DescendingOrdering: return CSharpFeaturesResources.orderby_clause; case SyntaxKind.SelectClause: return CSharpFeaturesResources.select_clause; case SyntaxKind.GroupClause: return CSharpFeaturesResources.groupby_clause; case SyntaxKind.QueryBody: return CSharpFeaturesResources.query_body; case SyntaxKind.QueryContinuation: return CSharpFeaturesResources.into_clause; case SyntaxKind.IsPatternExpression: return CSharpFeaturesResources.is_pattern; case SyntaxKind.SimpleAssignmentExpression: if (((AssignmentExpressionSyntax)node).IsDeconstruction()) { return CSharpFeaturesResources.deconstruction; } else { throw ExceptionUtilities.UnexpectedValue(node.Kind()); } case SyntaxKind.TupleType: case SyntaxKind.TupleExpression: return CSharpFeaturesResources.tuple; case SyntaxKind.LocalFunctionStatement: return CSharpFeaturesResources.local_function; case SyntaxKind.DeclarationExpression: return CSharpFeaturesResources.out_var; case SyntaxKind.RefType: case SyntaxKind.RefExpression: return CSharpFeaturesResources.ref_local_or_expression; case SyntaxKind.SwitchStatement: return CSharpFeaturesResources.switch_statement; case SyntaxKind.LocalDeclarationStatement: if (((LocalDeclarationStatementSyntax)node).UsingKeyword.IsKind(SyntaxKind.UsingKeyword)) { return CSharpFeaturesResources.using_declaration; } return CSharpFeaturesResources.local_variable_declaration; default: return null; } } protected override string GetSuspensionPointDisplayName(SyntaxNode node, EditKind editKind) { switch (node.Kind()) { case SyntaxKind.ForEachStatement: Debug.Assert(((CommonForEachStatementSyntax)node).AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword)); return CSharpFeaturesResources.asynchronous_foreach_statement; case SyntaxKind.VariableDeclarator: RoslynDebug.Assert(((LocalDeclarationStatementSyntax)node.Parent!.Parent!).AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword)); return CSharpFeaturesResources.asynchronous_using_declaration; default: return base.GetSuspensionPointDisplayName(node, editKind); } } #endregion #region Top-Level Syntactic Rude Edits private readonly struct EditClassifier { private readonly CSharpEditAndContinueAnalyzer _analyzer; private readonly ArrayBuilder<RudeEditDiagnostic> _diagnostics; private readonly Match<SyntaxNode>? _match; private readonly SyntaxNode? _oldNode; private readonly SyntaxNode? _newNode; private readonly EditKind _kind; private readonly TextSpan? _span; public EditClassifier( CSharpEditAndContinueAnalyzer analyzer, ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode? oldNode, SyntaxNode? newNode, EditKind kind, Match<SyntaxNode>? match = null, TextSpan? span = null) { RoslynDebug.Assert(oldNode != null || newNode != null); // if the node is deleted we have map that can be used to closest new ancestor RoslynDebug.Assert(newNode != null || match != null); _analyzer = analyzer; _diagnostics = diagnostics; _oldNode = oldNode; _newNode = newNode; _kind = kind; _span = span; _match = match; } private void ReportError(RudeEditKind kind, SyntaxNode? spanNode = null, SyntaxNode? displayNode = null) { var span = (spanNode != null) ? GetDiagnosticSpan(spanNode, _kind) : GetSpan(); var node = displayNode ?? _newNode ?? _oldNode; var displayName = GetDisplayName(node!, _kind); _diagnostics.Add(new RudeEditDiagnostic(kind, span, node, arguments: new[] { displayName })); } private TextSpan GetSpan() { if (_span.HasValue) { return _span.Value; } if (_newNode == null) { return _analyzer.GetDeletedNodeDiagnosticSpan(_match!.Matches, _oldNode!); } return GetDiagnosticSpan(_newNode, _kind); } public void ClassifyEdit() { switch (_kind) { case EditKind.Delete: ClassifyDelete(_oldNode!); return; case EditKind.Update: ClassifyUpdate(_oldNode!, _newNode!); return; case EditKind.Move: ClassifyMove(_newNode!); return; case EditKind.Insert: ClassifyInsert(_newNode!); return; case EditKind.Reorder: ClassifyReorder(_newNode!); return; default: throw ExceptionUtilities.UnexpectedValue(_kind); } } private void ClassifyMove(SyntaxNode newNode) { if (newNode.IsKind(SyntaxKind.LocalFunctionStatement)) { return; } // We could perhaps allow moving a type declaration to a different namespace syntax node // as long as it represents semantically the same namespace as the one of the original type declaration. ReportError(RudeEditKind.Move); } private void ClassifyReorder(SyntaxNode newNode) { if (_newNode.IsKind(SyntaxKind.LocalFunctionStatement)) { return; } switch (newNode.Kind()) { case SyntaxKind.PropertyDeclaration: case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: case SyntaxKind.VariableDeclarator: // Maybe we could allow changing order of field declarations unless the containing type layout is sequential. ReportError(RudeEditKind.Move); return; case SyntaxKind.EnumMemberDeclaration: // To allow this change we would need to check that values of all fields of the enum // are preserved, or make sure we can update all method bodies that accessed those that changed. ReportError(RudeEditKind.Move); return; case SyntaxKind.TypeParameter: case SyntaxKind.Parameter: ReportError(RudeEditKind.Move); return; } } private void ClassifyInsert(SyntaxNode node) { switch (node.Kind()) { case SyntaxKind.ExternAliasDirective: case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: ReportError(RudeEditKind.Insert); return; case SyntaxKind.Attribute: case SyntaxKind.AttributeList: // To allow inserting of attributes we need to check if the inserted attribute // is a pseudo-custom attribute that CLR allows us to change, or if it is a compiler well-know attribute // that affects the generated IL, so we defer those checks until semantic analysis. // Unless the attribute is a module/assembly attribute if (node.IsParentKind(SyntaxKind.CompilationUnit) || node.Parent.IsParentKind(SyntaxKind.CompilationUnit)) { ReportError(RudeEditKind.Insert); } return; } } private void ClassifyDelete(SyntaxNode oldNode) { switch (oldNode.Kind()) { case SyntaxKind.ExternAliasDirective: case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: // To allow removal of declarations we would need to update method bodies that // were previously binding to them but now are binding to another symbol that was previously hidden. ReportError(RudeEditKind.Delete); return; case SyntaxKind.AttributeList: case SyntaxKind.Attribute: // To allow removal of attributes we need to check if the removed attribute // is a pseudo-custom attribute that CLR does not allow us to change, or if it is a compiler well-know attribute // that affects the generated IL, so we defer those checks until semantic analysis. // Unless the attribute is a module/assembly attribute if (oldNode.IsParentKind(SyntaxKind.CompilationUnit) || oldNode.Parent.IsParentKind(SyntaxKind.CompilationUnit)) { ReportError(RudeEditKind.Delete); } return; } } private void ClassifyUpdate(SyntaxNode oldNode, SyntaxNode newNode) { switch (newNode.Kind()) { case SyntaxKind.ExternAliasDirective: ReportError(RudeEditKind.Update); return; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: ClassifyUpdate((BaseNamespaceDeclarationSyntax)oldNode, (BaseNamespaceDeclarationSyntax)newNode); return; case SyntaxKind.Attribute: // To allow update of attributes we need to check if the updated attribute // is a pseudo-custom attribute that CLR allows us to change, or if it is a compiler well-know attribute // that affects the generated IL, so we defer those checks until semantic analysis. // Unless the attribute is a module/assembly attribute if (newNode.IsParentKind(SyntaxKind.CompilationUnit) || newNode.Parent.IsParentKind(SyntaxKind.CompilationUnit)) { ReportError(RudeEditKind.Update); } return; } } private void ClassifyUpdate(BaseNamespaceDeclarationSyntax oldNode, BaseNamespaceDeclarationSyntax newNode) { Debug.Assert(!SyntaxFactory.AreEquivalent(oldNode.Name, newNode.Name)); ReportError(RudeEditKind.Renamed); } public void ClassifyDeclarationBodyRudeUpdates(SyntaxNode newDeclarationOrBody) { foreach (var node in newDeclarationOrBody.DescendantNodesAndSelf(LambdaUtilities.IsNotLambda)) { switch (node.Kind()) { case SyntaxKind.StackAllocArrayCreationExpression: case SyntaxKind.ImplicitStackAllocArrayCreationExpression: ReportError(RudeEditKind.StackAllocUpdate, node, _newNode); return; } } } } internal override void ReportTopLevelSyntacticRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, Edit<SyntaxNode> edit, Dictionary<SyntaxNode, EditKind> editMap) { if (HasParentEdit(editMap, edit)) { return; } var classifier = new EditClassifier(this, diagnostics, edit.OldNode, edit.NewNode, edit.Kind, match); classifier.ClassifyEdit(); } internal override void ReportMemberBodyUpdateRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode newMember, TextSpan? span) { var classifier = new EditClassifier(this, diagnostics, oldNode: null, newMember, EditKind.Update, span: span); classifier.ClassifyDeclarationBodyRudeUpdates(newMember); } #endregion #region Semantic Rude Edits internal override void ReportInsertedMemberSymbolRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol newSymbol, SyntaxNode newNode, bool insertingIntoExistingContainingType) { var rudeEditKind = newSymbol switch { // Inserting extern member into a new or existing type is not allowed. { IsExtern: true } => RudeEditKind.InsertExtern, // All rude edits below only apply when inserting into an existing type (not when the type itself is inserted): _ when !insertingIntoExistingContainingType => RudeEditKind.None, // Inserting a member into an existing generic type is not allowed. { ContainingType: { Arity: > 0 } } and not INamedTypeSymbol => RudeEditKind.InsertIntoGenericType, // Inserting virtual or interface member into an existing type is not allowed. { IsVirtual: true } or { IsOverride: true } or { IsAbstract: true } and not INamedTypeSymbol => RudeEditKind.InsertVirtual, // Inserting generic method into an existing type is not allowed. IMethodSymbol { Arity: > 0 } => RudeEditKind.InsertGenericMethod, // Inserting destructor to an existing type is not allowed. IMethodSymbol { MethodKind: MethodKind.Destructor } => RudeEditKind.Insert, // Inserting operator to an existing type is not allowed. IMethodSymbol { MethodKind: MethodKind.Conversion or MethodKind.UserDefinedOperator } => RudeEditKind.InsertOperator, // Inserting a method that explictly implements an interface method into an existing type is not allowed. IMethodSymbol { ExplicitInterfaceImplementations: { IsEmpty: false } } => RudeEditKind.InsertMethodWithExplicitInterfaceSpecifier, // TODO: Inserting non-virtual member to an interface (https://github.com/dotnet/roslyn/issues/37128) { ContainingType: { TypeKind: TypeKind.Interface } } and not INamedTypeSymbol => RudeEditKind.InsertIntoInterface, // Inserting a field into an enum: #pragma warning disable format // https://github.com/dotnet/roslyn/issues/54759 IFieldSymbol { ContainingType.TypeKind: TypeKind.Enum } => RudeEditKind.Insert, #pragma warning restore format _ => RudeEditKind.None }; if (rudeEditKind != RudeEditKind.None) { diagnostics.Add(new RudeEditDiagnostic( rudeEditKind, GetDiagnosticSpan(newNode, EditKind.Insert), newNode, arguments: new[] { GetDisplayName(newNode, EditKind.Insert) })); } } #endregion #region Exception Handling Rude Edits /// <summary> /// Return nodes that represent exception handlers encompassing the given active statement node. /// </summary> protected override List<SyntaxNode> GetExceptionHandlingAncestors(SyntaxNode node, bool isNonLeaf) { var result = new List<SyntaxNode>(); var current = node; while (current != null) { var kind = current.Kind(); switch (kind) { case SyntaxKind.TryStatement: if (isNonLeaf) { result.Add(current); } break; case SyntaxKind.CatchClause: case SyntaxKind.FinallyClause: result.Add(current); // skip try: RoslynDebug.Assert(current.Parent is object); RoslynDebug.Assert(current.Parent.Kind() == SyntaxKind.TryStatement); current = current.Parent; break; // stop at type declaration: case SyntaxKind.ClassDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: return result; } // stop at lambda: if (LambdaUtilities.IsLambda(current)) { return result; } current = current.Parent; } return result; } internal override void ReportEnclosingExceptionHandlingRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, IEnumerable<Edit<SyntaxNode>> exceptionHandlingEdits, SyntaxNode oldStatement, TextSpan newStatementSpan) { foreach (var edit in exceptionHandlingEdits) { // try/catch/finally have distinct labels so only the nodes of the same kind may match: Debug.Assert(edit.Kind != EditKind.Update || edit.OldNode.RawKind == edit.NewNode.RawKind); if (edit.Kind != EditKind.Update || !AreExceptionClausesEquivalent(edit.OldNode, edit.NewNode)) { AddAroundActiveStatementRudeDiagnostic(diagnostics, edit.OldNode, edit.NewNode, newStatementSpan); } } } private static bool AreExceptionClausesEquivalent(SyntaxNode oldNode, SyntaxNode newNode) { switch (oldNode.Kind()) { case SyntaxKind.TryStatement: var oldTryStatement = (TryStatementSyntax)oldNode; var newTryStatement = (TryStatementSyntax)newNode; return SyntaxFactory.AreEquivalent(oldTryStatement.Finally, newTryStatement.Finally) && SyntaxFactory.AreEquivalent(oldTryStatement.Catches, newTryStatement.Catches); case SyntaxKind.CatchClause: case SyntaxKind.FinallyClause: return SyntaxFactory.AreEquivalent(oldNode, newNode); default: throw ExceptionUtilities.UnexpectedValue(oldNode.Kind()); } } /// <summary> /// An active statement (leaf or not) inside a "catch" makes the catch block read-only. /// An active statement (leaf or not) inside a "finally" makes the whole try/catch/finally block read-only. /// An active statement (non leaf) inside a "try" makes the catch/finally block read-only. /// </summary> /// <remarks> /// Exception handling regions are only needed to be tracked if they contain user code. /// <see cref="UsingStatementSyntax"/> and using <see cref="LocalDeclarationStatementSyntax"/> generate finally blocks, /// but they do not contain non-hidden sequence points. /// </remarks> /// <param name="node">An exception handling ancestor of an active statement node.</param> /// <param name="coversAllChildren"> /// True if all child nodes of the <paramref name="node"/> are contained in the exception region represented by the <paramref name="node"/>. /// </param> protected override TextSpan GetExceptionHandlingRegion(SyntaxNode node, out bool coversAllChildren) { TryStatementSyntax tryStatement; switch (node.Kind()) { case SyntaxKind.TryStatement: tryStatement = (TryStatementSyntax)node; coversAllChildren = false; if (tryStatement.Catches.Count == 0) { RoslynDebug.Assert(tryStatement.Finally != null); return tryStatement.Finally.Span; } return TextSpan.FromBounds( tryStatement.Catches.First().SpanStart, (tryStatement.Finally != null) ? tryStatement.Finally.Span.End : tryStatement.Catches.Last().Span.End); case SyntaxKind.CatchClause: coversAllChildren = true; return node.Span; case SyntaxKind.FinallyClause: coversAllChildren = true; tryStatement = (TryStatementSyntax)node.Parent!; return tryStatement.Span; default: throw ExceptionUtilities.UnexpectedValue(node.Kind()); } } #endregion #region State Machines internal override bool IsStateMachineMethod(SyntaxNode declaration) => SyntaxUtilities.IsAsyncDeclaration(declaration) || SyntaxUtilities.GetSuspensionPoints(declaration).Any(); protected override void GetStateMachineInfo(SyntaxNode body, out ImmutableArray<SyntaxNode> suspensionPoints, out StateMachineKinds kinds) { suspensionPoints = SyntaxUtilities.GetSuspensionPoints(body).ToImmutableArray(); kinds = StateMachineKinds.None; if (suspensionPoints.Any(n => n.IsKind(SyntaxKind.YieldBreakStatement) || n.IsKind(SyntaxKind.YieldReturnStatement))) { kinds |= StateMachineKinds.Iterator; } if (SyntaxUtilities.IsAsyncDeclaration(body.Parent)) { kinds |= StateMachineKinds.Async; } } internal override void ReportStateMachineSuspensionPointRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldNode, SyntaxNode newNode) { // TODO: changes around suspension points (foreach, lock, using, etc.) if (newNode.IsKind(SyntaxKind.AwaitExpression)) { var oldContainingStatementPart = FindContainingStatementPart(oldNode); var newContainingStatementPart = FindContainingStatementPart(newNode); // If the old statement has spilled state and the new doesn't the edit is ok. We'll just not use the spilled state. if (!SyntaxFactory.AreEquivalent(oldContainingStatementPart, newContainingStatementPart) && !HasNoSpilledState(newNode, newContainingStatementPart)) { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.AwaitStatementUpdate, newContainingStatementPart.Span)); } } } internal override void ReportStateMachineSuspensionPointDeletedRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode deletedSuspensionPoint) { // Handle deletion of await keyword from await foreach statement. if (deletedSuspensionPoint is CommonForEachStatementSyntax deletedForeachStatement && match.Matches.TryGetValue(deletedSuspensionPoint, out var newForEachStatement) && newForEachStatement is CommonForEachStatementSyntax && deletedForeachStatement.AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingFromAsynchronousToSynchronous, GetDiagnosticSpan(newForEachStatement, EditKind.Update), newForEachStatement, new[] { GetDisplayName(newForEachStatement, EditKind.Update) })); return; } // Handle deletion of await keyword from await using declaration. if (deletedSuspensionPoint.IsKind(SyntaxKind.VariableDeclarator) && match.Matches.TryGetValue(deletedSuspensionPoint.Parent!.Parent!, out var newLocalDeclaration) && !((LocalDeclarationStatementSyntax)newLocalDeclaration).AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingFromAsynchronousToSynchronous, GetDiagnosticSpan(newLocalDeclaration, EditKind.Update), newLocalDeclaration, new[] { GetDisplayName(newLocalDeclaration, EditKind.Update) })); return; } base.ReportStateMachineSuspensionPointDeletedRudeEdit(diagnostics, match, deletedSuspensionPoint); } internal override void ReportStateMachineSuspensionPointInsertedRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode insertedSuspensionPoint, bool aroundActiveStatement) { // Handle addition of await keyword to foreach statement. if (insertedSuspensionPoint is CommonForEachStatementSyntax insertedForEachStatement && match.ReverseMatches.TryGetValue(insertedSuspensionPoint, out var oldNode) && oldNode is CommonForEachStatementSyntax oldForEachStatement && !oldForEachStatement.AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.Insert, insertedForEachStatement.AwaitKeyword.Span, insertedForEachStatement, new[] { insertedForEachStatement.AwaitKeyword.ToString() })); return; } // Handle addition of using keyword to using declaration. if (insertedSuspensionPoint.IsKind(SyntaxKind.VariableDeclarator) && match.ReverseMatches.TryGetValue(insertedSuspensionPoint.Parent!.Parent!, out var oldLocalDeclaration) && !((LocalDeclarationStatementSyntax)oldLocalDeclaration).AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword)) { var newLocalDeclaration = (LocalDeclarationStatementSyntax)insertedSuspensionPoint!.Parent!.Parent!; diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.Insert, newLocalDeclaration.AwaitKeyword.Span, newLocalDeclaration, new[] { newLocalDeclaration.AwaitKeyword.ToString() })); return; } base.ReportStateMachineSuspensionPointInsertedRudeEdit(diagnostics, match, insertedSuspensionPoint, aroundActiveStatement); } private static SyntaxNode FindContainingStatementPart(SyntaxNode node) { while (true) { if (node is StatementSyntax statement) { return statement; } RoslynDebug.Assert(node is object); RoslynDebug.Assert(node.Parent is object); switch (node.Parent.Kind()) { case SyntaxKind.ForStatement: case SyntaxKind.ForEachStatement: case SyntaxKind.IfStatement: case SyntaxKind.WhileStatement: case SyntaxKind.DoStatement: case SyntaxKind.SwitchStatement: case SyntaxKind.LockStatement: case SyntaxKind.UsingStatement: case SyntaxKind.ArrowExpressionClause: return node; } if (LambdaUtilities.IsLambdaBodyStatementOrExpression(node)) { return node; } node = node.Parent; } } private static bool HasNoSpilledState(SyntaxNode awaitExpression, SyntaxNode containingStatementPart) { Debug.Assert(awaitExpression.IsKind(SyntaxKind.AwaitExpression)); // There is nothing within the statement part surrounding the await expression. if (containingStatementPart == awaitExpression) { return true; } switch (containingStatementPart.Kind()) { case SyntaxKind.ExpressionStatement: case SyntaxKind.ReturnStatement: var expression = GetExpressionFromStatementPart(containingStatementPart); // await expr; // return await expr; if (expression == awaitExpression) { return true; } // identifier = await expr; // return identifier = await expr; return IsSimpleAwaitAssignment(expression, awaitExpression); case SyntaxKind.VariableDeclaration: // var idf = await expr in using, for, etc. // EqualsValueClause -> VariableDeclarator -> VariableDeclaration return awaitExpression.Parent!.Parent!.Parent == containingStatementPart; case SyntaxKind.LocalDeclarationStatement: // var idf = await expr; // EqualsValueClause -> VariableDeclarator -> VariableDeclaration -> LocalDeclarationStatement return awaitExpression.Parent!.Parent!.Parent!.Parent == containingStatementPart; } return IsSimpleAwaitAssignment(containingStatementPart, awaitExpression); } private static ExpressionSyntax GetExpressionFromStatementPart(SyntaxNode statement) { switch (statement.Kind()) { case SyntaxKind.ExpressionStatement: return ((ExpressionStatementSyntax)statement).Expression; case SyntaxKind.ReturnStatement: // Must have an expression since we are only inspecting at statements that contain an expression. return ((ReturnStatementSyntax)statement).Expression!; default: throw ExceptionUtilities.UnexpectedValue(statement.Kind()); } } private static bool IsSimpleAwaitAssignment(SyntaxNode node, SyntaxNode awaitExpression) { if (node.IsKind(SyntaxKind.SimpleAssignmentExpression, out AssignmentExpressionSyntax? assignment)) { return assignment.Left.IsKind(SyntaxKind.IdentifierName) && assignment.Right == awaitExpression; } return false; } #endregion #region Rude Edits around Active Statement internal override void ReportOtherRudeEditsAroundActiveStatement( ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode oldActiveStatement, SyntaxNode newActiveStatement, bool isNonLeaf) { ReportRudeEditsForSwitchWhenClauses(diagnostics, oldActiveStatement, newActiveStatement); ReportRudeEditsForAncestorsDeclaringInterStatementTemps(diagnostics, match, oldActiveStatement, newActiveStatement); ReportRudeEditsForCheckedStatements(diagnostics, oldActiveStatement, newActiveStatement, isNonLeaf); } /// <summary> /// Reports rude edits when an active statement is a when clause in a switch statement and any of the switch cases or the switch value changed. /// This is necessary since the switch emits long-lived synthesized variables to store results of pattern evaluations. /// These synthesized variables are mapped to the slots of the new methods via ordinals. The mapping preserves the values of these variables as long as /// exactly the same variables are emitted for the new switch as they were for the old one and their order didn't change either. /// This is guaranteed if none of the case clauses have changed. /// </summary> private void ReportRudeEditsForSwitchWhenClauses(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldActiveStatement, SyntaxNode newActiveStatement) { if (!oldActiveStatement.IsKind(SyntaxKind.WhenClause)) { return; } // switch expression does not have sequence points (active statements): if (!(oldActiveStatement.Parent!.Parent!.Parent is SwitchStatementSyntax oldSwitch)) { return; } // switch statement does not match switch expression, so it must be part of a switch statement as well. var newSwitch = (SwitchStatementSyntax)newActiveStatement.Parent!.Parent!.Parent!; // when clauses can only match other when clauses: Debug.Assert(newActiveStatement.IsKind(SyntaxKind.WhenClause)); if (!AreEquivalentIgnoringLambdaBodies(oldSwitch.Expression, newSwitch.Expression)) { AddRudeUpdateAroundActiveStatement(diagnostics, newSwitch); } if (!AreEquivalentSwitchStatementDecisionTrees(oldSwitch, newSwitch)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.UpdateAroundActiveStatement, GetDiagnosticSpan(newSwitch, EditKind.Update), newSwitch, new[] { CSharpFeaturesResources.switch_statement_case_clause })); } } private static bool AreEquivalentSwitchStatementDecisionTrees(SwitchStatementSyntax oldSwitch, SwitchStatementSyntax newSwitch) => oldSwitch.Sections.SequenceEqual(newSwitch.Sections, AreSwitchSectionsEquivalent); private static bool AreSwitchSectionsEquivalent(SwitchSectionSyntax oldSection, SwitchSectionSyntax newSection) => oldSection.Labels.SequenceEqual(newSection.Labels, AreLabelsEquivalent); private static bool AreLabelsEquivalent(SwitchLabelSyntax oldLabel, SwitchLabelSyntax newLabel) { if (oldLabel.IsKind(SyntaxKind.CasePatternSwitchLabel, out CasePatternSwitchLabelSyntax? oldCasePatternLabel) && newLabel.IsKind(SyntaxKind.CasePatternSwitchLabel, out CasePatternSwitchLabelSyntax? newCasePatternLabel)) { // ignore the actual when expressions: return SyntaxFactory.AreEquivalent(oldCasePatternLabel.Pattern, newCasePatternLabel.Pattern) && (oldCasePatternLabel.WhenClause != null) == (newCasePatternLabel.WhenClause != null); } else { return SyntaxFactory.AreEquivalent(oldLabel, newLabel); } } private void ReportRudeEditsForCheckedStatements( ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldActiveStatement, SyntaxNode newActiveStatement, bool isNonLeaf) { // checked context can't be changed around non-leaf active statement: if (!isNonLeaf) { return; } // Changing checked context around an internal active statement may change the instructions // executed after method calls in the active statement but before the next sequence point. // Since the debugger remaps the IP at the first sequence point following a call instruction // allowing overflow context to be changed may lead to execution of code with old semantics. var oldCheckedStatement = TryGetCheckedStatementAncestor(oldActiveStatement); var newCheckedStatement = TryGetCheckedStatementAncestor(newActiveStatement); bool isRude; if (oldCheckedStatement == null || newCheckedStatement == null) { isRude = oldCheckedStatement != newCheckedStatement; } else { isRude = oldCheckedStatement.Kind() != newCheckedStatement.Kind(); } if (isRude) { AddAroundActiveStatementRudeDiagnostic(diagnostics, oldCheckedStatement, newCheckedStatement, newActiveStatement.Span); } } private static CheckedStatementSyntax? TryGetCheckedStatementAncestor(SyntaxNode? node) { // Ignoring lambda boundaries since checked context flows through. while (node != null) { switch (node.Kind()) { case SyntaxKind.CheckedStatement: case SyntaxKind.UncheckedStatement: return (CheckedStatementSyntax)node; } node = node.Parent; } return null; } private void ReportRudeEditsForAncestorsDeclaringInterStatementTemps( ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode oldActiveStatement, SyntaxNode newActiveStatement) { // Rude Edits for fixed/using/lock/foreach statements that are added/updated around an active statement. // Although such changes are technically possible, they might lead to confusion since // the temporary variables these statements generate won't be properly initialized. // // We use a simple algorithm to match each new node with its old counterpart. // If all nodes match this algorithm is linear, otherwise it's quadratic. // // Unlike exception regions matching where we use LCS, we allow reordering of the statements. ReportUnmatchedStatements<LockStatementSyntax>(diagnostics, match, n => n.IsKind(SyntaxKind.LockStatement), oldActiveStatement, newActiveStatement, areEquivalent: AreEquivalentActiveStatements, areSimilar: null); ReportUnmatchedStatements<FixedStatementSyntax>(diagnostics, match, n => n.IsKind(SyntaxKind.FixedStatement), oldActiveStatement, newActiveStatement, areEquivalent: AreEquivalentActiveStatements, areSimilar: (n1, n2) => DeclareSameIdentifiers(n1.Declaration.Variables, n2.Declaration.Variables)); // Using statements with declaration do not introduce compiler generated temporary. ReportUnmatchedStatements<UsingStatementSyntax>( diagnostics, match, n => n.IsKind(SyntaxKind.UsingStatement, out UsingStatementSyntax? usingStatement) && usingStatement.Declaration is null, oldActiveStatement, newActiveStatement, areEquivalent: AreEquivalentActiveStatements, areSimilar: null); ReportUnmatchedStatements<CommonForEachStatementSyntax>( diagnostics, match, n => n.IsKind(SyntaxKind.ForEachStatement) || n.IsKind(SyntaxKind.ForEachVariableStatement), oldActiveStatement, newActiveStatement, areEquivalent: AreEquivalentActiveStatements, areSimilar: AreSimilarActiveStatements); } private static bool DeclareSameIdentifiers(SeparatedSyntaxList<VariableDeclaratorSyntax> oldVariables, SeparatedSyntaxList<VariableDeclaratorSyntax> newVariables) => DeclareSameIdentifiers(oldVariables.Select(v => v.Identifier).ToArray(), newVariables.Select(v => v.Identifier).ToArray()); private static bool DeclareSameIdentifiers(SyntaxToken[] oldVariables, SyntaxToken[] newVariables) { if (oldVariables.Length != newVariables.Length) { return false; } for (var i = 0; i < oldVariables.Length; i++) { if (!SyntaxFactory.AreEquivalent(oldVariables[i], newVariables[i])) { return false; } } return true; } #endregion } }
1
dotnet/roslyn
55,409
Use FixedSize API
tmat
2021-08-04T19:30:40Z
2021-08-04T21:53:46Z
e0112742bff208dd0546de45e36f7b52058a45a3
c90bf0ec986010051662c8e1fbc872c2fd86bc4e
Use FixedSize API.
./src/Features/Core/Portable/EditAndContinue/AbstractEditAndContinueAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Differencing; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { internal abstract class AbstractEditAndContinueAnalyzer : IEditAndContinueAnalyzer { internal const int DefaultStatementPart = 0; private const string CreateNewOnMetadataUpdateAttributeName = "CreateNewOnMetadataUpdateAttribute"; /// <summary> /// Contains enough information to determine whether two symbols have the same signature. /// </summary> private static readonly SymbolDisplayFormat s_unqualifiedMemberDisplayFormat = new( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameOnly, propertyStyle: SymbolDisplayPropertyStyle.NameOnly, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeExplicitInterface, parameterOptions: SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeExtensionThis | SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes); private static readonly SymbolDisplayFormat s_fullyQualifiedMemberDisplayFormat = new( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, propertyStyle: SymbolDisplayPropertyStyle.NameOnly, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeContainingType, parameterOptions: SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeExtensionThis | SymbolDisplayParameterOptions.IncludeType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes); // used by tests to validate correct handlign of unexpected exceptions private readonly Action<SyntaxNode>? _testFaultInjector; protected AbstractEditAndContinueAnalyzer(Action<SyntaxNode>? testFaultInjector) { _testFaultInjector = testFaultInjector; } internal abstract bool ExperimentalFeaturesEnabled(SyntaxTree tree); /// <summary> /// Finds member declaration node(s) containing given <paramref name="node"/>. /// Specified <paramref name="node"/> may be either a node of the declaration body or an active node that belongs to the declaration. /// </summary> /// <remarks> /// The implementation has to decide what kinds of nodes in top-level match relationship represent a declaration. /// Every member declaration must be represented by exactly one node, but not all nodes have to represent a declaration. /// /// Note that in some cases the set of nodes of the declaration body may differ from the set of active nodes that /// belong to the declaration. For example, in <c>Dim a, b As New T</c> the sets for member <c>a</c> are /// { <c>New</c>, <c>T</c> } and { <c>a</c> }, respectively. /// /// May return multiple declarations if the specified <paramref name="node"/> belongs to multiple declarations, /// such as in VB <c>Dim a, b As New T</c> case when <paramref name="node"/> is e.g. <c>T</c>. /// </remarks> internal abstract bool TryFindMemberDeclaration(SyntaxNode? root, SyntaxNode node, out OneOrMany<SyntaxNode> declarations); /// <summary> /// If the specified node represents a member declaration returns a node that represents its body, /// i.e. a node used as the root of statement-level match. /// </summary> /// <param name="node">A node representing a declaration or a top-level edit node.</param> /// /// <returns> /// Returns null for nodes that don't represent declarations. /// </returns> /// <remarks> /// The implementation has to decide what kinds of nodes in top-level match relationship represent a declaration. /// Every member declaration must be represented by exactly one node, but not all nodes have to represent a declaration. /// /// If a member doesn't have a body (null is returned) it can't have associated active statements. /// /// Body does not need to cover all active statements that may be associated with the member. /// E.g. Body of a C# constructor is the method body block. Active statements may be placed on the base constructor call. /// Body of a VB field declaration with shared AsNew initializer is the New expression. Active statements might be placed on the field variables. /// <see cref="FindStatementAndPartner"/> has to account for such cases. /// </remarks> internal abstract SyntaxNode? TryGetDeclarationBody(SyntaxNode node); /// <summary> /// True if the specified <paramref name="declaration"/> node shares body with another declaration. /// </summary> internal abstract bool IsDeclarationWithSharedBody(SyntaxNode declaration); /// <summary> /// If the specified node represents a member declaration returns all tokens of the member declaration /// that might be covered by an active statement. /// </summary> /// <returns> /// Tokens covering all possible breakpoint spans associated with the member, /// or null if the specified node doesn't represent a member declaration or /// doesn't have a body that can contain active statements. /// </returns> /// <remarks> /// The implementation has to decide what kinds of nodes in top-level match relationship represent a declaration. /// Every member declaration must be represented by exactly one node, but not all nodes have to represent a declaration. /// /// TODO: consider implementing this via <see cref="GetActiveSpanEnvelope"/>. /// </remarks> internal abstract IEnumerable<SyntaxToken>? TryGetActiveTokens(SyntaxNode node); /// <summary> /// Returns a span that contains all possible breakpoint spans of the <paramref name="declaration"/> /// and no breakpoint spans that do not belong to the <paramref name="declaration"/>. /// /// Returns default if the declaration does not have any breakpoint spans. /// </summary> internal abstract (TextSpan envelope, TextSpan hole) GetActiveSpanEnvelope(SyntaxNode declaration); /// <summary> /// Returns an ancestor that encompasses all active and statement level /// nodes that belong to the member represented by <paramref name="bodyOrMatchRoot"/>. /// </summary> protected SyntaxNode? GetEncompassingAncestor(SyntaxNode? bodyOrMatchRoot) { if (bodyOrMatchRoot == null) { return null; } var root = GetEncompassingAncestorImpl(bodyOrMatchRoot); Debug.Assert(root.Span.Contains(bodyOrMatchRoot.Span)); return root; } protected abstract SyntaxNode GetEncompassingAncestorImpl(SyntaxNode bodyOrMatchRoot); /// <summary> /// Finds a statement at given span and a declaration body. /// Also returns the corresponding partner statement in <paramref name="partnerDeclarationBody"/>, if specified. /// </summary> /// <remarks> /// The declaration body node may not contain the <paramref name="span"/>. /// This happens when an active statement associated with the member is outside of its body /// (e.g. C# constructor, or VB <c>Dim a,b As New T</c>). /// If the position doesn't correspond to any statement uses the start of the <paramref name="declarationBody"/>. /// </remarks> protected abstract SyntaxNode FindStatementAndPartner(SyntaxNode declarationBody, TextSpan span, SyntaxNode? partnerDeclarationBody, out SyntaxNode? partner, out int statementPart); private SyntaxNode FindStatement(SyntaxNode declarationBody, TextSpan span, out int statementPart) => FindStatementAndPartner(declarationBody, span, null, out _, out statementPart); /// <summary> /// Maps <paramref name="leftNode"/> of a body of <paramref name="leftDeclaration"/> to corresponding body node /// of <paramref name="rightDeclaration"/>, assuming that the declaration bodies only differ in trivia. /// </summary> internal abstract SyntaxNode FindDeclarationBodyPartner(SyntaxNode leftDeclaration, SyntaxNode rightDeclaration, SyntaxNode leftNode); /// <summary> /// Returns a node that represents a body of a lambda containing specified <paramref name="node"/>, /// or null if the node isn't contained in a lambda. If a node is returned it must uniquely represent the lambda, /// i.e. be no two distinct nodes may represent the same lambda. /// </summary> protected abstract SyntaxNode? FindEnclosingLambdaBody(SyntaxNode? container, SyntaxNode node); /// <summary> /// Given a node that represents a lambda body returns all nodes of the body in a syntax list. /// </summary> /// <remarks> /// Note that VB lambda bodies are represented by a lambda header and that some lambda bodies share /// their parent nodes with other bodies (e.g. join clause expressions). /// </remarks> protected abstract IEnumerable<SyntaxNode> GetLambdaBodyExpressionsAndStatements(SyntaxNode lambdaBody); protected abstract SyntaxNode? TryGetPartnerLambdaBody(SyntaxNode oldBody, SyntaxNode newLambda); protected abstract Match<SyntaxNode> ComputeTopLevelMatch(SyntaxNode oldCompilationUnit, SyntaxNode newCompilationUnit); protected abstract Match<SyntaxNode> ComputeBodyMatch(SyntaxNode oldBody, SyntaxNode newBody, IEnumerable<KeyValuePair<SyntaxNode, SyntaxNode>>? knownMatches); protected abstract Match<SyntaxNode> ComputeTopLevelDeclarationMatch(SyntaxNode oldDeclaration, SyntaxNode newDeclaration); protected abstract IEnumerable<SequenceEdit> GetSyntaxSequenceEdits(ImmutableArray<SyntaxNode> oldNodes, ImmutableArray<SyntaxNode> newNodes); /// <summary> /// Matches old active statement to new active statement without constructing full method body match. /// This is needed for active statements that are outside of method body, like constructor initializer. /// </summary> protected abstract bool TryMatchActiveStatement( SyntaxNode oldStatement, int statementPart, SyntaxNode oldBody, SyntaxNode newBody, [NotNullWhen(true)] out SyntaxNode? newStatement); protected abstract bool TryGetEnclosingBreakpointSpan(SyntaxNode root, int position, out TextSpan span); /// <summary> /// Get the active span that corresponds to specified node (or its part). /// </summary> /// <returns> /// True if the node has an active span associated with it, false otherwise. /// </returns> protected abstract bool TryGetActiveSpan(SyntaxNode node, int statementPart, int minLength, out TextSpan span); /// <summary> /// Yields potential active statements around the specified active statement /// starting with siblings following the statement, then preceding the statement, follows with its parent, its following siblings, etc. /// </summary> /// <returns> /// Pairs of (node, statement part), or (node, -1) indicating there is no logical following statement. /// The enumeration continues until the root is reached. /// </returns> protected abstract IEnumerable<(SyntaxNode statement, int statementPart)> EnumerateNearStatements(SyntaxNode statement); protected abstract bool StatementLabelEquals(SyntaxNode node1, SyntaxNode node2); /// <summary> /// True if both nodes represent the same kind of suspension point /// (await expression, await foreach statement, await using declarator, yield return, yield break). /// </summary> protected virtual bool StateMachineSuspensionPointKindEquals(SyntaxNode suspensionPoint1, SyntaxNode suspensionPoint2) => suspensionPoint1.RawKind == suspensionPoint2.RawKind; /// <summary> /// Determines if two syntax nodes are the same, disregarding trivia differences. /// </summary> protected abstract bool AreEquivalent(SyntaxNode left, SyntaxNode right); /// <summary> /// Returns true if the code emitted for the old active statement part (<paramref name="statementPart"/> of <paramref name="oldStatement"/>) /// is the same as the code emitted for the corresponding new active statement part (<paramref name="statementPart"/> of <paramref name="newStatement"/>). /// </summary> /// <remarks> /// A rude edit is reported if an active statement is changed and this method returns true. /// </remarks> protected abstract bool AreEquivalentActiveStatements(SyntaxNode oldStatement, SyntaxNode newStatement, int statementPart); protected abstract TextSpan GetGlobalStatementDiagnosticSpan(SyntaxNode node); /// <summary> /// Returns all symbols associated with an edit and an actual edit kind, which may be different then the specified one. /// Returns an empty set if the edit is not associated with any symbols. /// </summary> protected abstract OneOrMany<(ISymbol? oldSymbol, ISymbol? newSymbol, EditKind editKind)> GetSymbolEdits( EditKind editKind, SyntaxNode? oldNode, SyntaxNode? newNode, SemanticModel? oldModel, SemanticModel newModel, IReadOnlyDictionary<SyntaxNode, EditKind> editMap, CancellationToken cancellationToken); /// <summary> /// Analyzes data flow in the member body represented by the specified node and returns all captured variables and parameters (including "this"). /// If the body is a field/property initializer analyzes the initializer expression only. /// </summary> protected abstract ImmutableArray<ISymbol> GetCapturedVariables(SemanticModel model, SyntaxNode memberBody); /// <summary> /// Enumerates all use sites of a specified variable within the specified syntax subtrees. /// </summary> protected abstract IEnumerable<SyntaxNode> GetVariableUseSites(IEnumerable<SyntaxNode> roots, ISymbol localOrParameter, SemanticModel model, CancellationToken cancellationToken); protected abstract bool AreFixedSizeBufferSizesEqual(IFieldSymbol oldField, IFieldSymbol newField, CancellationToken cancellationToken); protected abstract bool AreHandledEventsEqual(IMethodSymbol oldMethod, IMethodSymbol newMethod); // diagnostic spans: protected abstract TextSpan? TryGetDiagnosticSpan(SyntaxNode node, EditKind editKind); internal TextSpan GetDiagnosticSpan(SyntaxNode node, EditKind editKind) => TryGetDiagnosticSpan(node, editKind) ?? node.Span; protected virtual TextSpan GetBodyDiagnosticSpan(SyntaxNode node, EditKind editKind) { var current = node.Parent; while (true) { if (current == null) { return node.Span; } var span = TryGetDiagnosticSpan(current, editKind); if (span != null) { return span.Value; } current = current.Parent; } } internal abstract TextSpan GetLambdaParameterDiagnosticSpan(SyntaxNode lambda, int ordinal); // display names: internal string GetDisplayName(SyntaxNode node, EditKind editKind = EditKind.Update) => TryGetDisplayName(node, editKind) ?? throw ExceptionUtilities.UnexpectedValue(node.GetType().Name); internal string GetDisplayName(ISymbol symbol) => symbol.Kind switch { SymbolKind.Event => FeaturesResources.event_, SymbolKind.Field => GetDisplayName((IFieldSymbol)symbol), SymbolKind.Method => GetDisplayName((IMethodSymbol)symbol), SymbolKind.NamedType => GetDisplayName((INamedTypeSymbol)symbol), SymbolKind.Parameter => FeaturesResources.parameter, SymbolKind.Property => GetDisplayName((IPropertySymbol)symbol), SymbolKind.TypeParameter => FeaturesResources.type_parameter, _ => throw ExceptionUtilities.UnexpectedValue(symbol.Kind) }; internal virtual string GetDisplayName(IPropertySymbol symbol) => FeaturesResources.property_; internal virtual string GetDisplayName(INamedTypeSymbol symbol) => symbol.TypeKind switch { TypeKind.Class => FeaturesResources.class_, TypeKind.Interface => FeaturesResources.interface_, TypeKind.Delegate => FeaturesResources.delegate_, TypeKind.Enum => FeaturesResources.enum_, TypeKind.TypeParameter => FeaturesResources.type_parameter, _ => FeaturesResources.type, }; internal virtual string GetDisplayName(IFieldSymbol symbol) => symbol.IsConst ? ((symbol.ContainingType.TypeKind == TypeKind.Enum) ? FeaturesResources.enum_value : FeaturesResources.const_field) : FeaturesResources.field; internal virtual string GetDisplayName(IMethodSymbol symbol) => symbol.MethodKind switch { MethodKind.Constructor => FeaturesResources.constructor, MethodKind.PropertyGet or MethodKind.PropertySet => FeaturesResources.property_accessor, MethodKind.EventAdd or MethodKind.EventRaise or MethodKind.EventRemove => FeaturesResources.event_accessor, MethodKind.BuiltinOperator or MethodKind.UserDefinedOperator or MethodKind.Conversion => FeaturesResources.operator_, _ => FeaturesResources.method, }; /// <summary> /// Returns the display name of an ancestor node that contains the specified node and has a display name. /// </summary> protected virtual string GetBodyDisplayName(SyntaxNode node, EditKind editKind = EditKind.Update) { var current = node.Parent; while (true) { if (current == null) { throw ExceptionUtilities.UnexpectedValue(node.GetType().Name); } var displayName = TryGetDisplayName(current, editKind); if (displayName != null) { return displayName; } current = current.Parent; } } protected abstract string? TryGetDisplayName(SyntaxNode node, EditKind editKind); protected virtual string GetSuspensionPointDisplayName(SyntaxNode node, EditKind editKind) => GetDisplayName(node, editKind); protected abstract string LineDirectiveKeyword { get; } protected abstract ushort LineDirectiveSyntaxKind { get; } protected abstract SymbolDisplayFormat ErrorDisplayFormat { get; } protected abstract List<SyntaxNode> GetExceptionHandlingAncestors(SyntaxNode node, bool isNonLeaf); protected abstract void GetStateMachineInfo(SyntaxNode body, out ImmutableArray<SyntaxNode> suspensionPoints, out StateMachineKinds kinds); protected abstract TextSpan GetExceptionHandlingRegion(SyntaxNode node, out bool coversAllChildren); protected abstract void ReportLocalFunctionsDeclarationRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> bodyMatch); internal abstract void ReportTopLevelSyntacticRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, Edit<SyntaxNode> edit, Dictionary<SyntaxNode, EditKind> editMap); internal abstract void ReportEnclosingExceptionHandlingRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, IEnumerable<Edit<SyntaxNode>> exceptionHandlingEdits, SyntaxNode oldStatement, TextSpan newStatementSpan); internal abstract void ReportOtherRudeEditsAroundActiveStatement(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode oldStatement, SyntaxNode newStatement, bool isNonLeaf); internal abstract void ReportMemberBodyUpdateRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode newMember, TextSpan? span); internal abstract void ReportInsertedMemberSymbolRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol newSymbol, SyntaxNode newNode, bool insertingIntoExistingContainingType); internal abstract void ReportStateMachineSuspensionPointRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldNode, SyntaxNode newNode); internal abstract bool IsLambda(SyntaxNode node); internal abstract bool IsInterfaceDeclaration(SyntaxNode node); internal abstract bool IsRecordDeclaration(SyntaxNode node); /// <summary> /// True if the node represents any form of a function definition nested in another function body (i.e. anonymous function, lambda, local function). /// </summary> internal abstract bool IsNestedFunction(SyntaxNode node); internal abstract bool IsLocalFunction(SyntaxNode node); internal abstract bool IsClosureScope(SyntaxNode node); internal abstract bool ContainsLambda(SyntaxNode declaration); internal abstract SyntaxNode GetLambda(SyntaxNode lambdaBody); internal abstract IMethodSymbol GetLambdaExpressionSymbol(SemanticModel model, SyntaxNode lambdaExpression, CancellationToken cancellationToken); internal abstract SyntaxNode? GetContainingQueryExpression(SyntaxNode node); internal abstract bool QueryClauseLambdasTypeEquivalent(SemanticModel oldModel, SyntaxNode oldNode, SemanticModel newModel, SyntaxNode newNode, CancellationToken cancellationToken); /// <summary> /// Returns true if the parameters of the symbol are lifted into a scope that is different from the symbol's body. /// </summary> internal abstract bool HasParameterClosureScope(ISymbol member); /// <summary> /// Returns all lambda bodies of a node representing a lambda, /// or false if the node doesn't represent a lambda. /// </summary> /// <remarks> /// C# anonymous function expression and VB lambda expression both have a single body /// (in VB the body is the header of the lambda expression). /// /// Some lambda queries (group by, join by) have two bodies. /// </remarks> internal abstract bool TryGetLambdaBodies(SyntaxNode node, [NotNullWhen(true)] out SyntaxNode? body1, out SyntaxNode? body2); internal abstract bool IsStateMachineMethod(SyntaxNode declaration); /// <summary> /// Returns the type declaration that contains a specified <paramref name="node"/>. /// This can be class, struct, interface, record or enum declaration. /// </summary> internal abstract SyntaxNode? TryGetContainingTypeDeclaration(SyntaxNode node); /// <summary> /// Returns the declaration of /// - a property, indexer or event declaration whose accessor is the specified <paramref name="node"/>, /// - a method, an indexer or a type (delegate) if the <paramref name="node"/> is a parameter, /// - a method or an type if the <paramref name="node"/> is a type parameter. /// </summary> internal abstract bool TryGetAssociatedMemberDeclaration(SyntaxNode node, [NotNullWhen(true)] out SyntaxNode? declaration); internal abstract bool HasBackingField(SyntaxNode propertyDeclaration); /// <summary> /// Return true if the declaration is a field/property declaration with an initializer. /// Shall return false for enum members. /// </summary> internal abstract bool IsDeclarationWithInitializer(SyntaxNode declaration); /// <summary> /// Return true if the declaration is a parameter that is part of a records primary constructor. /// </summary> internal abstract bool IsRecordPrimaryConstructorParameter(SyntaxNode declaration); /// <summary> /// Return true if the declaration is a property accessor for a property that represents one of the parameters in a records primary constructor. /// </summary> internal abstract bool IsPropertyAccessorDeclarationMatchingPrimaryConstructorParameter(SyntaxNode declaration, INamedTypeSymbol newContainingType, out bool isFirstAccessor); /// <summary> /// Return true if the declaration is a constructor declaration to which field/property initializers are emitted. /// </summary> internal abstract bool IsConstructorWithMemberInitializers(SyntaxNode declaration); internal abstract bool IsPartial(INamedTypeSymbol type); internal abstract SyntaxNode EmptyCompilationUnit { get; } private static readonly SourceText s_emptySource = SourceText.From(""); #region Document Analysis public async Task<DocumentAnalysisResults> AnalyzeDocumentAsync( Project oldProject, ActiveStatementsMap oldActiveStatementMap, Document newDocument, ImmutableArray<LinePositionSpan> newActiveStatementSpans, EditAndContinueCapabilities capabilities, CancellationToken cancellationToken) { DocumentAnalysisResults.Log.Write("Analyzing document {0}", newDocument.Name); Debug.Assert(!newActiveStatementSpans.IsDefault); Debug.Assert(newDocument.SupportsSyntaxTree); Debug.Assert(newDocument.SupportsSemanticModel); // assume changes until we determine there are none so that EnC is blocked on unexpected exception: var hasChanges = true; try { cancellationToken.ThrowIfCancellationRequested(); SyntaxTree? oldTree; SyntaxNode oldRoot; SourceText oldText; var oldDocument = await oldProject.GetDocumentAsync(newDocument.Id, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); if (oldDocument != null) { oldTree = await oldDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(oldTree); oldRoot = await oldTree.GetRootAsync(cancellationToken).ConfigureAwait(false); oldText = await oldDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); } else { oldTree = null; oldRoot = EmptyCompilationUnit; oldText = s_emptySource; } var newTree = await newDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(newTree); // Changes in parse options might change the meaning of the code even if nothing else changed. // The IDE should disallow changing the options during debugging session. Debug.Assert(oldTree == null || oldTree.Options.Equals(newTree.Options)); var newRoot = await newTree.GetRootAsync(cancellationToken).ConfigureAwait(false); var newText = await newDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); hasChanges = !oldText.ContentEquals(newText); _testFaultInjector?.Invoke(newRoot); cancellationToken.ThrowIfCancellationRequested(); // TODO: newTree.HasErrors? var syntaxDiagnostics = newRoot.GetDiagnostics(); var hasSyntaxError = syntaxDiagnostics.Any(d => d.Severity == DiagnosticSeverity.Error); if (hasSyntaxError) { // Bail, since we can't do syntax diffing on broken trees (it would not produce useful results anyways). // If we needed to do so for some reason, we'd need to harden the syntax tree comparers. DocumentAnalysisResults.Log.Write("{0}: syntax errors", newDocument.Name); return DocumentAnalysisResults.SyntaxErrors(newDocument.Id, ImmutableArray<RudeEditDiagnostic>.Empty, hasChanges); } if (!hasChanges) { // The document might have been closed and reopened, which might have triggered analysis. // If the document is unchanged don't continue the analysis since // a) comparing texts is cheaper than diffing trees // b) we need to ignore errors in unchanged documents DocumentAnalysisResults.Log.Write("{0}: unchanged", newDocument.Name); return DocumentAnalysisResults.Unchanged(newDocument.Id); } // If the document has changed at all, lets make sure Edit and Continue is supported if (!capabilities.HasFlag(EditAndContinueCapabilities.Baseline)) { return DocumentAnalysisResults.SyntaxErrors(newDocument.Id, ImmutableArray.Create( new RudeEditDiagnostic(RudeEditKind.NotSupportedByRuntime, default)), hasChanges); } // Disallow modification of a file with experimental features enabled. // These features may not be handled well by the analysis below. if (ExperimentalFeaturesEnabled(newTree)) { DocumentAnalysisResults.Log.Write("{0}: experimental features enabled", newDocument.Name); return DocumentAnalysisResults.SyntaxErrors(newDocument.Id, ImmutableArray.Create( new RudeEditDiagnostic(RudeEditKind.ExperimentalFeaturesEnabled, default)), hasChanges); } // We are in break state when there are no active statements. var inBreakState = !oldActiveStatementMap.IsEmpty; // We do calculate diffs even if there are semantic errors for the following reasons: // 1) We need to be able to find active spans in the new document. // If we didn't calculate them we would only rely on tracking spans (might be ok). // 2) If there are syntactic rude edits we'll report them faster without waiting for semantic analysis. // The user may fix them before they address all the semantic errors. using var _2 = ArrayBuilder<RudeEditDiagnostic>.GetInstance(out var diagnostics); cancellationToken.ThrowIfCancellationRequested(); var topMatch = ComputeTopLevelMatch(oldRoot, newRoot); var syntacticEdits = topMatch.GetTreeEdits(); var editMap = BuildEditMap(syntacticEdits); var hasRudeEdits = false; ReportTopLevelSyntacticRudeEdits(diagnostics, syntacticEdits, editMap); if (diagnostics.Count > 0 && !hasRudeEdits) { DocumentAnalysisResults.Log.Write("{0} syntactic rude edits, first: '{1}'", diagnostics.Count, newDocument.FilePath); hasRudeEdits = true; } cancellationToken.ThrowIfCancellationRequested(); using var _3 = ArrayBuilder<(SyntaxNode OldNode, SyntaxNode NewNode, TextSpan DiagnosticSpan)>.GetInstance(out var triviaEdits); using var _4 = ArrayBuilder<SequencePointUpdates>.GetInstance(out var lineEdits); AnalyzeTrivia( topMatch, editMap, triviaEdits, lineEdits, cancellationToken); cancellationToken.ThrowIfCancellationRequested(); var oldActiveStatements = (oldTree == null) ? ImmutableArray<UnmappedActiveStatement>.Empty : oldActiveStatementMap.GetOldActiveStatements(this, oldTree, oldText, oldRoot, cancellationToken); var newActiveStatements = ImmutableArray.CreateBuilder<ActiveStatement>(oldActiveStatements.Length); newActiveStatements.Count = oldActiveStatements.Length; var newExceptionRegions = ImmutableArray.CreateBuilder<ImmutableArray<SourceFileSpan>>(oldActiveStatements.Length); newExceptionRegions.Count = oldActiveStatements.Length; var semanticEdits = await AnalyzeSemanticsAsync( syntacticEdits, editMap, oldActiveStatements, newActiveStatementSpans, triviaEdits, oldProject, oldDocument, newDocument, newText, diagnostics, newActiveStatements, newExceptionRegions, capabilities, inBreakState, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); AnalyzeUnchangedActiveMemberBodies(diagnostics, syntacticEdits.Match, newText, oldActiveStatements, newActiveStatementSpans, newActiveStatements, newExceptionRegions, cancellationToken); Debug.Assert(newActiveStatements.All(a => a != null)); if (diagnostics.Count > 0 && !hasRudeEdits) { DocumentAnalysisResults.Log.Write("{0}@{1}: rude edit ({2} total)", newDocument.FilePath, diagnostics.First().Span.Start, diagnostics.Count); hasRudeEdits = true; } return new DocumentAnalysisResults( newDocument.Id, newActiveStatements.MoveToImmutable(), diagnostics.ToImmutable(), hasRudeEdits ? default : semanticEdits, hasRudeEdits ? default : newExceptionRegions.MoveToImmutable(), hasRudeEdits ? default : lineEdits.ToImmutable(), hasChanges: true, hasSyntaxErrors: false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { // The same behavior as if there was a syntax error - we are unable to analyze the document. // We expect OOM to be thrown during the analysis if the number of top-level entities is too large. // In such case we report a rude edit for the document. If the host is actually running out of memory, // it might throw another OOM here or later on. var diagnostic = (e is OutOfMemoryException) ? new RudeEditDiagnostic(RudeEditKind.SourceFileTooBig, span: default, arguments: new[] { newDocument.FilePath }) : new RudeEditDiagnostic(RudeEditKind.InternalError, span: default, arguments: new[] { newDocument.FilePath, e.ToString() }); // Report as "syntax error" - we can't analyze the document return DocumentAnalysisResults.SyntaxErrors(newDocument.Id, ImmutableArray.Create(diagnostic), hasChanges); } } private void ReportTopLevelSyntacticRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, EditScript<SyntaxNode> syntacticEdits, Dictionary<SyntaxNode, EditKind> editMap) { foreach (var edit in syntacticEdits.Edits) { ReportTopLevelSyntacticRudeEdits(diagnostics, syntacticEdits.Match, edit, editMap); } } /// <summary> /// Reports rude edits for a symbol that's been deleted in one location and inserted in another and the edit was not classified as /// <see cref="EditKind.Move"/> or <see cref="EditKind.Reorder"/>. /// The scenarios include moving a type declaration from one file to another and moving a member of a partial type from one partial declaration to another. /// </summary> internal virtual void ReportDeclarationInsertDeleteRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldNode, SyntaxNode newNode, ISymbol oldSymbol, ISymbol newSymbol, CancellationToken cancellationToken) { // When a method is moved to a different declaration and its parameters are changed at the same time // the new method symbol key will not resolve to the old one since the parameters are different. // As a result we will report separate delete and insert rude edits. // // For delegates, however, the symbol key will resolve to the old type so we need to report // rude edits here. if (oldSymbol is INamedTypeSymbol { DelegateInvokeMethod: not null and var oldDelegateInvoke } && newSymbol is INamedTypeSymbol { DelegateInvokeMethod: not null and var newDelegateInvoke }) { if (!ParametersEquivalent(oldDelegateInvoke.Parameters, newDelegateInvoke.Parameters, exact: false)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingParameterTypes, newSymbol, newNode, cancellationToken); } } } internal static Dictionary<SyntaxNode, EditKind> BuildEditMap(EditScript<SyntaxNode> editScript) { var map = new Dictionary<SyntaxNode, EditKind>(editScript.Edits.Length); foreach (var edit in editScript.Edits) { // do not include reorder and move edits if (edit.Kind is EditKind.Delete or EditKind.Update) { map.Add(edit.OldNode, edit.Kind); } if (edit.Kind is EditKind.Insert or EditKind.Update) { map.Add(edit.NewNode, edit.Kind); } } return map; } #endregion #region Syntax Analysis private void AnalyzeUnchangedActiveMemberBodies( ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> topMatch, SourceText newText, ImmutableArray<UnmappedActiveStatement> oldActiveStatements, ImmutableArray<LinePositionSpan> newActiveStatementSpans, [In, Out] ImmutableArray<ActiveStatement>.Builder newActiveStatements, [In, Out] ImmutableArray<ImmutableArray<SourceFileSpan>>.Builder newExceptionRegions, CancellationToken cancellationToken) { Debug.Assert(!newActiveStatementSpans.IsDefault); Debug.Assert(newActiveStatementSpans.IsEmpty || oldActiveStatements.Length == newActiveStatementSpans.Length); Debug.Assert(oldActiveStatements.Length == newActiveStatements.Count); Debug.Assert(oldActiveStatements.Length == newExceptionRegions.Count); // Active statements in methods that were not updated // are not changed but their spans might have been. for (var i = 0; i < newActiveStatements.Count; i++) { if (newActiveStatements[i] == null) { Contract.ThrowIfFalse(newExceptionRegions[i].IsDefault); var oldStatementSpan = oldActiveStatements[i].UnmappedSpan; var node = TryGetNode(topMatch.OldRoot, oldStatementSpan.Start); // Guard against invalid active statement spans (in case PDB was somehow out of sync with the source). if (node != null && TryFindMemberDeclaration(topMatch.OldRoot, node, out var oldMemberDeclarations)) { foreach (var oldMember in oldMemberDeclarations) { var hasPartner = topMatch.TryGetNewNode(oldMember, out var newMember); Contract.ThrowIfFalse(hasPartner); var oldBody = TryGetDeclarationBody(oldMember); var newBody = TryGetDeclarationBody(newMember); // Guard against invalid active statement spans (in case PDB was somehow out of sync with the source). if (oldBody == null || newBody == null) { DocumentAnalysisResults.Log.Write("Invalid active statement span: [{0}..{1})", oldStatementSpan.Start, oldStatementSpan.End); continue; } var statementPart = -1; SyntaxNode? newStatement = null; // We seed the method body matching algorithm with tracking spans (unless they were deleted) // to get precise matching. if (TryGetTrackedStatement(newActiveStatementSpans, i, newText, newMember, newBody, out var trackedStatement, out var trackedStatementPart)) { // Adjust for active statements that cover more than the old member span. // For example, C# variable declarators that represent field initializers: // [|public int <<F = Expr()>>;|] var adjustedOldStatementStart = oldMember.FullSpan.Contains(oldStatementSpan.Start) ? oldStatementSpan.Start : oldMember.SpanStart; // The tracking span might have been moved outside of lambda. // It is not an error to move the statement - we just ignore it. var oldEnclosingLambdaBody = FindEnclosingLambdaBody(oldBody, oldMember.FindToken(adjustedOldStatementStart).Parent!); var newEnclosingLambdaBody = FindEnclosingLambdaBody(newBody, trackedStatement); if (oldEnclosingLambdaBody == newEnclosingLambdaBody) { newStatement = trackedStatement; statementPart = trackedStatementPart; } } if (newStatement == null) { Contract.ThrowIfFalse(statementPart == -1); FindStatementAndPartner(oldBody, oldStatementSpan, newBody, out newStatement, out statementPart); Contract.ThrowIfNull(newStatement); } if (diagnostics.Count == 0) { var ancestors = GetExceptionHandlingAncestors(newStatement, oldActiveStatements[i].Statement.IsNonLeaf); newExceptionRegions[i] = GetExceptionRegions(ancestors, newStatement.SyntaxTree, cancellationToken).Spans; } // Even though the body of the declaration haven't changed, // changes to its header might have caused the active span to become unavailable. // (e.g. In C# "const" was added to modifiers of a field with an initializer). var newStatementSpan = FindClosestActiveSpan(newStatement, statementPart); newActiveStatements[i] = GetActiveStatementWithSpan(oldActiveStatements[i], newBody.SyntaxTree, newStatementSpan, diagnostics, cancellationToken); } } else { DocumentAnalysisResults.Log.Write("Invalid active statement span: [{0}..{1})", oldStatementSpan.Start, oldStatementSpan.End); } // we were not able to determine the active statement location (PDB data might be invalid) if (newActiveStatements[i] == null) { newActiveStatements[i] = oldActiveStatements[i].Statement.WithSpan(default); newExceptionRegions[i] = ImmutableArray<SourceFileSpan>.Empty; } } } } internal readonly struct ActiveNode { public readonly int ActiveStatementIndex; public readonly SyntaxNode OldNode; public readonly SyntaxNode? NewTrackedNode; public readonly SyntaxNode? EnclosingLambdaBody; public readonly int StatementPart; public ActiveNode(int activeStatementIndex, SyntaxNode oldNode, SyntaxNode? enclosingLambdaBody, int statementPart, SyntaxNode? newTrackedNode) { ActiveStatementIndex = activeStatementIndex; OldNode = oldNode; NewTrackedNode = newTrackedNode; EnclosingLambdaBody = enclosingLambdaBody; StatementPart = statementPart; } } /// <summary> /// Information about an active and/or a matched lambda. /// </summary> internal readonly struct LambdaInfo { // non-null for an active lambda (lambda containing an active statement) public readonly List<int>? ActiveNodeIndices; // both fields are non-null for a matching lambda (lambda that exists in both old and new document): public readonly Match<SyntaxNode>? Match; public readonly SyntaxNode? NewBody; public LambdaInfo(List<int> activeNodeIndices) : this(activeNodeIndices, null, null) { } private LambdaInfo(List<int>? activeNodeIndices, Match<SyntaxNode>? match, SyntaxNode? newLambdaBody) { ActiveNodeIndices = activeNodeIndices; Match = match; NewBody = newLambdaBody; } public LambdaInfo WithMatch(Match<SyntaxNode> match, SyntaxNode newLambdaBody) => new(ActiveNodeIndices, match, newLambdaBody); } private void AnalyzeChangedMemberBody( SyntaxNode oldDeclaration, SyntaxNode newDeclaration, SyntaxNode oldBody, SyntaxNode? newBody, SemanticModel oldModel, SemanticModel newModel, ISymbol oldSymbol, ISymbol newSymbol, SourceText newText, ImmutableArray<UnmappedActiveStatement> oldActiveStatements, ImmutableArray<LinePositionSpan> newActiveStatementSpans, EditAndContinueCapabilities capabilities, [Out] ImmutableArray<ActiveStatement>.Builder newActiveStatements, [Out] ImmutableArray<ImmutableArray<SourceFileSpan>>.Builder newExceptionRegions, [Out] ArrayBuilder<RudeEditDiagnostic> diagnostics, out Func<SyntaxNode, SyntaxNode?>? syntaxMap, CancellationToken cancellationToken) { Debug.Assert(!newActiveStatementSpans.IsDefault); Debug.Assert(newActiveStatementSpans.IsEmpty || oldActiveStatements.Length == newActiveStatementSpans.Length); Debug.Assert(oldActiveStatements.IsEmpty || oldActiveStatements.Length == newActiveStatements.Count); Debug.Assert(newActiveStatements.Count == newExceptionRegions.Count); syntaxMap = null; var activeStatementIndices = GetOverlappingActiveStatements(oldDeclaration, oldActiveStatements); if (newBody == null) { // The body has been deleted. var newSpan = FindClosestActiveSpan(newDeclaration, DefaultStatementPart); Debug.Assert(newSpan != default); foreach (var activeStatementIndex in activeStatementIndices) { // We have already calculated the new location of this active statement when analyzing another member declaration. // This may only happen when two or more member declarations share the same body (VB AsNew clause). if (newActiveStatements[activeStatementIndex] != null) { Debug.Assert(IsDeclarationWithSharedBody(newDeclaration)); continue; } newActiveStatements[activeStatementIndex] = GetActiveStatementWithSpan(oldActiveStatements[activeStatementIndex], newDeclaration.SyntaxTree, newSpan, diagnostics, cancellationToken); newExceptionRegions[activeStatementIndex] = ImmutableArray<SourceFileSpan>.Empty; } return; } try { ReportMemberBodyUpdateRudeEdits(diagnostics, newDeclaration, GetDiagnosticSpan(newDeclaration, EditKind.Update)); _testFaultInjector?.Invoke(newBody); // Populated with active lambdas and matched lambdas. // Unmatched non-active lambdas are not included. // { old-lambda-body -> info } Dictionary<SyntaxNode, LambdaInfo>? lazyActiveOrMatchedLambdas = null; // finds leaf nodes that correspond to the old active statements: using var _ = ArrayBuilder<ActiveNode>.GetInstance(out var activeNodes); foreach (var activeStatementIndex in activeStatementIndices) { var oldStatementSpan = oldActiveStatements[activeStatementIndex].UnmappedSpan; var oldStatementSyntax = FindStatement(oldBody, oldStatementSpan, out var statementPart); Contract.ThrowIfNull(oldStatementSyntax); var oldEnclosingLambdaBody = FindEnclosingLambdaBody(oldBody, oldStatementSyntax); if (oldEnclosingLambdaBody != null) { lazyActiveOrMatchedLambdas ??= new Dictionary<SyntaxNode, LambdaInfo>(); if (!lazyActiveOrMatchedLambdas.TryGetValue(oldEnclosingLambdaBody, out var lambda)) { lambda = new LambdaInfo(new List<int>()); lazyActiveOrMatchedLambdas.Add(oldEnclosingLambdaBody, lambda); } lambda.ActiveNodeIndices!.Add(activeNodes.Count); } SyntaxNode? trackedNode = null; if (TryGetTrackedStatement(newActiveStatementSpans, activeStatementIndex, newText, newDeclaration, newBody, out var newStatementSyntax, out var _)) { var newEnclosingLambdaBody = FindEnclosingLambdaBody(newBody, newStatementSyntax); // The tracking span might have been moved outside of the lambda span. // It is not an error to move the statement - we just ignore it. if (oldEnclosingLambdaBody == newEnclosingLambdaBody && StatementLabelEquals(oldStatementSyntax, newStatementSyntax)) { trackedNode = newStatementSyntax; } } activeNodes.Add(new ActiveNode(activeStatementIndex, oldStatementSyntax, oldEnclosingLambdaBody, statementPart, trackedNode)); } var bodyMatch = ComputeBodyMatch(oldBody, newBody, activeNodes.Where(n => n.EnclosingLambdaBody == null).ToArray(), diagnostics, out var oldHasStateMachineSuspensionPoint, out var newHasStateMachineSuspensionPoint); var map = ComputeMap(bodyMatch, activeNodes, ref lazyActiveOrMatchedLambdas, diagnostics); if (oldHasStateMachineSuspensionPoint) { ReportStateMachineRudeEdits(oldModel.Compilation, oldSymbol, newBody, diagnostics); } else if (newHasStateMachineSuspensionPoint && !capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)) { // Adding a state machine, either for async or iterator, will require creating a new helper class // so is a rude edit if the runtime doesn't support it if (newSymbol is IMethodSymbol { IsAsync: true }) { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.MakeMethodAsync, GetDiagnosticSpan(newDeclaration, EditKind.Insert))); } else { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.MakeMethodIterator, GetDiagnosticSpan(newDeclaration, EditKind.Insert))); } } ReportLambdaAndClosureRudeEdits( oldModel, oldBody, newModel, newBody, newSymbol, lazyActiveOrMatchedLambdas, map, capabilities, diagnostics, out var newBodyHasLambdas, cancellationToken); // We need to provide syntax map to the compiler if // 1) The new member has a active statement // The values of local variables declared or synthesized in the method have to be preserved. // 2) The new member generates a state machine // In case the state machine is suspended we need to preserve variables. // 3) The new member contains lambdas // We need to map new lambdas in the method to the matching old ones. // If the old method has lambdas but the new one doesn't there is nothing to preserve. // 4) Constructor that emits initializers is updated. // We create syntax map even if it's not necessary: if any data member initializers are active/contain lambdas. // Since initializers are usually simple the map should not be large enough to make it worth optimizing it away. if (!activeNodes.IsEmpty() || newHasStateMachineSuspensionPoint || newBodyHasLambdas || IsConstructorWithMemberInitializers(newDeclaration) || IsDeclarationWithInitializer(oldDeclaration) || IsDeclarationWithInitializer(newDeclaration)) { syntaxMap = CreateSyntaxMap(map.Reverse); } foreach (var activeNode in activeNodes) { var activeStatementIndex = activeNode.ActiveStatementIndex; var hasMatching = false; var isNonLeaf = oldActiveStatements[activeStatementIndex].Statement.IsNonLeaf; var isPartiallyExecuted = (oldActiveStatements[activeStatementIndex].Statement.Flags & ActiveStatementFlags.PartiallyExecuted) != 0; var statementPart = activeNode.StatementPart; var oldStatementSyntax = activeNode.OldNode; var oldEnclosingLambdaBody = activeNode.EnclosingLambdaBody; newExceptionRegions[activeStatementIndex] = ImmutableArray<SourceFileSpan>.Empty; TextSpan newSpan; SyntaxNode? newStatementSyntax; Match<SyntaxNode>? match; if (oldEnclosingLambdaBody == null) { match = bodyMatch; hasMatching = TryMatchActiveStatement(oldStatementSyntax, statementPart, oldBody, newBody, out newStatementSyntax) || match.TryGetNewNode(oldStatementSyntax, out newStatementSyntax); } else { RoslynDebug.Assert(lazyActiveOrMatchedLambdas != null); var oldLambdaInfo = lazyActiveOrMatchedLambdas[oldEnclosingLambdaBody]; var newEnclosingLambdaBody = oldLambdaInfo.NewBody; match = oldLambdaInfo.Match; if (match != null) { RoslynDebug.Assert(newEnclosingLambdaBody != null); // matching lambda has body hasMatching = TryMatchActiveStatement(oldStatementSyntax, statementPart, oldEnclosingLambdaBody, newEnclosingLambdaBody, out newStatementSyntax) || match.TryGetNewNode(oldStatementSyntax, out newStatementSyntax); } else { // Lambda match is null if lambdas can't be matched, // in such case we won't have active statement matched either. hasMatching = false; newStatementSyntax = null; } } if (hasMatching) { RoslynDebug.Assert(newStatementSyntax != null); RoslynDebug.Assert(match != null); // The matching node doesn't produce sequence points. // E.g. "const" keyword is inserted into a local variable declaration with an initializer. newSpan = FindClosestActiveSpan(newStatementSyntax, statementPart); if ((isNonLeaf || isPartiallyExecuted) && !AreEquivalentActiveStatements(oldStatementSyntax, newStatementSyntax, statementPart)) { // rude edit: non-leaf active statement changed diagnostics.Add(new RudeEditDiagnostic(isNonLeaf ? RudeEditKind.ActiveStatementUpdate : RudeEditKind.PartiallyExecutedActiveStatementUpdate, newSpan)); } // other statements around active statement: ReportOtherRudeEditsAroundActiveStatement(diagnostics, match, oldStatementSyntax, newStatementSyntax, isNonLeaf); } else if (match == null) { RoslynDebug.Assert(oldEnclosingLambdaBody != null); RoslynDebug.Assert(lazyActiveOrMatchedLambdas != null); newSpan = GetDeletedNodeDiagnosticSpan(oldEnclosingLambdaBody, bodyMatch, lazyActiveOrMatchedLambdas); // Lambda containing the active statement can't be found in the new source. var oldLambda = GetLambda(oldEnclosingLambdaBody); diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.ActiveStatementLambdaRemoved, newSpan, oldLambda, new[] { GetDisplayName(oldLambda) })); } else { newSpan = GetDeletedNodeActiveSpan(match.Matches, oldStatementSyntax); if (isNonLeaf || isPartiallyExecuted) { // rude edit: internal active statement deleted diagnostics.Add( new RudeEditDiagnostic(isNonLeaf ? RudeEditKind.DeleteActiveStatement : RudeEditKind.PartiallyExecutedActiveStatementDelete, GetDeletedNodeDiagnosticSpan(match.Matches, oldStatementSyntax), arguments: new[] { FeaturesResources.code })); } } // exception handling around the statement: CalculateExceptionRegionsAroundActiveStatement( bodyMatch, oldStatementSyntax, newStatementSyntax, newSpan, activeStatementIndex, isNonLeaf, newExceptionRegions, diagnostics, cancellationToken); // We have already calculated the new location of this active statement when analyzing another member declaration. // This may only happen when two or more member declarations share the same body (VB AsNew clause). Debug.Assert(IsDeclarationWithSharedBody(newDeclaration) || newActiveStatements[activeStatementIndex] == null); Debug.Assert(newSpan != default); newActiveStatements[activeStatementIndex] = GetActiveStatementWithSpan(oldActiveStatements[activeStatementIndex], newDeclaration.SyntaxTree, newSpan, diagnostics, cancellationToken); } } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { // Set the new spans of active statements overlapping the method body to match the old spans. // Even though these might be now outside of the method body it's ok since we report a rude edit and don't allow to continue. foreach (var i in activeStatementIndices) { newActiveStatements[i] = oldActiveStatements[i].Statement; newExceptionRegions[i] = ImmutableArray<SourceFileSpan>.Empty; } // We expect OOM to be thrown during the analysis if the number of statements is too large. // In such case we report a rude edit for the document. If the host is actually running out of memory, // it might throw another OOM here or later on. diagnostics.Add(new RudeEditDiagnostic( (e is OutOfMemoryException) ? RudeEditKind.MemberBodyTooBig : RudeEditKind.MemberBodyInternalError, GetBodyDiagnosticSpan(newBody, EditKind.Update), newBody, arguments: new[] { GetBodyDisplayName(newBody) })); } } private bool TryGetTrackedStatement(ImmutableArray<LinePositionSpan> activeStatementSpans, int index, SourceText text, SyntaxNode declaration, SyntaxNode body, [NotNullWhen(true)] out SyntaxNode? trackedStatement, out int trackedStatementPart) { trackedStatement = null; trackedStatementPart = -1; // Active statements are not tracked in this document (e.g. the file is closed). if (activeStatementSpans.IsEmpty) { return false; } var trackedLineSpan = activeStatementSpans[index]; if (trackedLineSpan == default) { return false; } var trackedSpan = text.Lines.GetTextSpan(trackedLineSpan); // The tracking span might have been deleted or moved outside of the member span. // It is not an error to move the statement - we just ignore it. // Consider: Instead of checking here, explicitly handle all cases when active statements can be outside of the body in FindStatement and // return false if the requested span is outside of the active envelope. var (envelope, hole) = GetActiveSpanEnvelope(declaration); if (!envelope.Contains(trackedSpan) || hole.Contains(trackedSpan)) { return false; } trackedStatement = FindStatement(body, trackedSpan, out trackedStatementPart); return true; } private ActiveStatement GetActiveStatementWithSpan(UnmappedActiveStatement oldStatement, SyntaxTree newTree, TextSpan newSpan, ArrayBuilder<RudeEditDiagnostic> diagnostics, CancellationToken cancellationToken) { var mappedLineSpan = newTree.GetMappedLineSpan(newSpan, cancellationToken); if (mappedLineSpan.HasMappedPath && mappedLineSpan.Path != oldStatement.Statement.FileSpan.Path) { // changing the source file of an active statement diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.UpdateAroundActiveStatement, newSpan, LineDirectiveSyntaxKind, arguments: new[] { string.Format(FeaturesResources._0_directive, LineDirectiveKeyword) })); } return oldStatement.Statement.WithFileSpan(mappedLineSpan); } private void CalculateExceptionRegionsAroundActiveStatement( Match<SyntaxNode> bodyMatch, SyntaxNode oldStatementSyntax, SyntaxNode? newStatementSyntax, TextSpan newStatementSyntaxSpan, int ordinal, bool isNonLeaf, ImmutableArray<ImmutableArray<SourceFileSpan>>.Builder newExceptionRegions, ArrayBuilder<RudeEditDiagnostic> diagnostics, CancellationToken cancellationToken) { if (newStatementSyntax == null) { if (!bodyMatch.NewRoot.Span.Contains(newStatementSyntaxSpan.Start)) { return; } newStatementSyntax = bodyMatch.NewRoot.FindToken(newStatementSyntaxSpan.Start).Parent; Contract.ThrowIfNull(newStatementSyntax); } var oldAncestors = GetExceptionHandlingAncestors(oldStatementSyntax, isNonLeaf); var newAncestors = GetExceptionHandlingAncestors(newStatementSyntax, isNonLeaf); if (oldAncestors.Count > 0 || newAncestors.Count > 0) { var edits = bodyMatch.GetSequenceEdits(oldAncestors, newAncestors); ReportEnclosingExceptionHandlingRudeEdits(diagnostics, edits, oldStatementSyntax, newStatementSyntaxSpan); // Exception regions are not needed in presence of errors. if (diagnostics.Count == 0) { Debug.Assert(oldAncestors.Count == newAncestors.Count); newExceptionRegions[ordinal] = GetExceptionRegions(newAncestors, newStatementSyntax.SyntaxTree, cancellationToken).Spans; } } } /// <summary> /// Calculates a syntax map of the entire method body including all lambda bodies it contains (recursively). /// </summary> private BidirectionalMap<SyntaxNode> ComputeMap( Match<SyntaxNode> bodyMatch, ArrayBuilder<ActiveNode> activeNodes, ref Dictionary<SyntaxNode, LambdaInfo>? lazyActiveOrMatchedLambdas, ArrayBuilder<RudeEditDiagnostic> diagnostics) { ArrayBuilder<Match<SyntaxNode>>? lambdaBodyMatches = null; var currentLambdaBodyMatch = -1; var currentBodyMatch = bodyMatch; while (true) { foreach (var (oldNode, newNode) in currentBodyMatch.Matches) { // Skip root, only enumerate body matches. if (oldNode == currentBodyMatch.OldRoot) { Debug.Assert(newNode == currentBodyMatch.NewRoot); continue; } if (TryGetLambdaBodies(oldNode, out var oldLambdaBody1, out var oldLambdaBody2)) { lambdaBodyMatches ??= ArrayBuilder<Match<SyntaxNode>>.GetInstance(); lazyActiveOrMatchedLambdas ??= new Dictionary<SyntaxNode, LambdaInfo>(); var newLambdaBody1 = TryGetPartnerLambdaBody(oldLambdaBody1, newNode); if (newLambdaBody1 != null) { lambdaBodyMatches.Add(ComputeLambdaBodyMatch(oldLambdaBody1, newLambdaBody1, activeNodes, lazyActiveOrMatchedLambdas, diagnostics)); } if (oldLambdaBody2 != null) { var newLambdaBody2 = TryGetPartnerLambdaBody(oldLambdaBody2, newNode); if (newLambdaBody2 != null) { lambdaBodyMatches.Add(ComputeLambdaBodyMatch(oldLambdaBody2, newLambdaBody2, activeNodes, lazyActiveOrMatchedLambdas, diagnostics)); } } } } currentLambdaBodyMatch++; if (lambdaBodyMatches == null || currentLambdaBodyMatch == lambdaBodyMatches.Count) { break; } currentBodyMatch = lambdaBodyMatches[currentLambdaBodyMatch]; } if (lambdaBodyMatches == null) { return BidirectionalMap<SyntaxNode>.FromMatch(bodyMatch); } var map = new Dictionary<SyntaxNode, SyntaxNode>(); var reverseMap = new Dictionary<SyntaxNode, SyntaxNode>(); // include all matches, including the root: map.AddRange(bodyMatch.Matches); reverseMap.AddRange(bodyMatch.ReverseMatches); foreach (var lambdaBodyMatch in lambdaBodyMatches) { foreach (var pair in lambdaBodyMatch.Matches) { if (!map.ContainsKey(pair.Key)) { map[pair.Key] = pair.Value; reverseMap[pair.Value] = pair.Key; } } } lambdaBodyMatches?.Free(); return new BidirectionalMap<SyntaxNode>(map, reverseMap); } private Match<SyntaxNode> ComputeLambdaBodyMatch( SyntaxNode oldLambdaBody, SyntaxNode newLambdaBody, IReadOnlyList<ActiveNode> activeNodes, [Out] Dictionary<SyntaxNode, LambdaInfo> activeOrMatchedLambdas, [Out] ArrayBuilder<RudeEditDiagnostic> diagnostics) { ActiveNode[]? activeNodesInLambda; if (activeOrMatchedLambdas.TryGetValue(oldLambdaBody, out var info)) { // Lambda may be matched but not be active. activeNodesInLambda = info.ActiveNodeIndices?.Select(i => activeNodes[i]).ToArray(); } else { // If the lambda body isn't in the map it doesn't have any active/tracked statements. activeNodesInLambda = null; info = new LambdaInfo(); } var lambdaBodyMatch = ComputeBodyMatch(oldLambdaBody, newLambdaBody, activeNodesInLambda ?? Array.Empty<ActiveNode>(), diagnostics, out _, out _); activeOrMatchedLambdas[oldLambdaBody] = info.WithMatch(lambdaBodyMatch, newLambdaBody); return lambdaBodyMatch; } private Match<SyntaxNode> ComputeBodyMatch( SyntaxNode oldBody, SyntaxNode newBody, ActiveNode[] activeNodes, ArrayBuilder<RudeEditDiagnostic> diagnostics, out bool oldHasStateMachineSuspensionPoint, out bool newHasStateMachineSuspensionPoint) { List<KeyValuePair<SyntaxNode, SyntaxNode>>? lazyKnownMatches = null; List<SequenceEdit>? lazyRudeEdits = null; GetStateMachineInfo(oldBody, out var oldStateMachineSuspensionPoints, out var oldStateMachineKinds); GetStateMachineInfo(newBody, out var newStateMachineSuspensionPoints, out var newStateMachineKinds); AddMatchingActiveNodes(ref lazyKnownMatches, activeNodes); // Consider following cases: // 1) Both old and new methods contain yields/awaits. // Map the old suspension points to new ones, report errors for added/deleted suspension points. // 2) The old method contains yields/awaits but the new doesn't. // Report rude edits for each deleted yield/await. // 3) The new method contains yields/awaits but the old doesn't. // a) If the method has active statements report rude edits for each inserted yield/await (insert "around" an active statement). // b) If the method has no active statements then the edit is valid, we don't need to calculate map. // 4) The old method is async/iterator, the new method is not and it contains an active statement. // Report rude edit since we can't remap IP from MoveNext to the kickoff method. // Note that iterators in VB don't need to contain yield, so this case is not covered by change in number of yields. var creatingStateMachineAroundActiveStatement = oldStateMachineSuspensionPoints.Length == 0 && newStateMachineSuspensionPoints.Length > 0 && activeNodes.Length > 0; oldHasStateMachineSuspensionPoint = oldStateMachineSuspensionPoints.Length > 0; newHasStateMachineSuspensionPoint = newStateMachineSuspensionPoints.Length > 0; if (oldStateMachineSuspensionPoints.Length > 0 || creatingStateMachineAroundActiveStatement) { AddMatchingStateMachineSuspensionPoints(ref lazyKnownMatches, ref lazyRudeEdits, oldStateMachineSuspensionPoints, newStateMachineSuspensionPoints); } var match = ComputeBodyMatch(oldBody, newBody, lazyKnownMatches); if (IsLocalFunction(match.OldRoot) && IsLocalFunction(match.NewRoot)) { ReportLocalFunctionsDeclarationRudeEdits(diagnostics, match); } if (lazyRudeEdits != null) { foreach (var rudeEdit in lazyRudeEdits) { if (rudeEdit.Kind == EditKind.Delete) { var deletedNode = oldStateMachineSuspensionPoints[rudeEdit.OldIndex]; ReportStateMachineSuspensionPointDeletedRudeEdit(diagnostics, match, deletedNode); } else { Debug.Assert(rudeEdit.Kind == EditKind.Insert); var insertedNode = newStateMachineSuspensionPoints[rudeEdit.NewIndex]; ReportStateMachineSuspensionPointInsertedRudeEdit(diagnostics, match, insertedNode, creatingStateMachineAroundActiveStatement); } } } else if (oldStateMachineSuspensionPoints.Length > 0) { Debug.Assert(oldStateMachineSuspensionPoints.Length == newStateMachineSuspensionPoints.Length); for (var i = 0; i < oldStateMachineSuspensionPoints.Length; i++) { var oldNode = oldStateMachineSuspensionPoints[i]; var newNode = newStateMachineSuspensionPoints[i]; // changing yield return to yield break, await to await foreach, yield to await, etc. if (StateMachineSuspensionPointKindEquals(oldNode, newNode)) { Debug.Assert(StatementLabelEquals(oldNode, newNode)); } else { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingStateMachineShape, newNode.Span, newNode, new[] { GetSuspensionPointDisplayName(oldNode, EditKind.Update), GetSuspensionPointDisplayName(newNode, EditKind.Update) })); } ReportStateMachineSuspensionPointRudeEdits(diagnostics, oldNode, newNode); } } else if (activeNodes.Length > 0) { // It is allowed to update a regular method to an async method or an iterator. // The only restriction is a presence of an active statement in the method body // since the debugger does not support remapping active statements to a different method. if (oldStateMachineKinds != newStateMachineKinds) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, GetBodyDiagnosticSpan(newBody, EditKind.Update))); } } // report removing async as rude: if (lazyRudeEdits == null) { if ((oldStateMachineKinds & StateMachineKinds.Async) != 0 && (newStateMachineKinds & StateMachineKinds.Async) == 0) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingFromAsynchronousToSynchronous, GetBodyDiagnosticSpan(newBody, EditKind.Update), newBody, new[] { GetBodyDisplayName(newBody) })); } // VB supports iterator lambdas/methods without yields if ((oldStateMachineKinds & StateMachineKinds.Iterator) != 0 && (newStateMachineKinds & StateMachineKinds.Iterator) == 0) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ModifiersUpdate, GetBodyDiagnosticSpan(newBody, EditKind.Update), newBody, new[] { GetBodyDisplayName(newBody) })); } } return match; } internal virtual void ReportStateMachineSuspensionPointDeletedRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode deletedSuspensionPoint) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.Delete, GetDeletedNodeDiagnosticSpan(match.Matches, deletedSuspensionPoint), deletedSuspensionPoint, new[] { GetSuspensionPointDisplayName(deletedSuspensionPoint, EditKind.Delete) })); } internal virtual void ReportStateMachineSuspensionPointInsertedRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode insertedSuspensionPoint, bool aroundActiveStatement) { diagnostics.Add(new RudeEditDiagnostic( aroundActiveStatement ? RudeEditKind.InsertAroundActiveStatement : RudeEditKind.Insert, GetDiagnosticSpan(insertedSuspensionPoint, EditKind.Insert), insertedSuspensionPoint, new[] { GetSuspensionPointDisplayName(insertedSuspensionPoint, EditKind.Insert) })); } private static void AddMatchingActiveNodes(ref List<KeyValuePair<SyntaxNode, SyntaxNode>>? lazyKnownMatches, IEnumerable<ActiveNode> activeNodes) { // add nodes that are tracked by the editor buffer to known matches: foreach (var activeNode in activeNodes) { if (activeNode.NewTrackedNode != null) { lazyKnownMatches ??= new List<KeyValuePair<SyntaxNode, SyntaxNode>>(); lazyKnownMatches.Add(KeyValuePairUtil.Create(activeNode.OldNode, activeNode.NewTrackedNode)); } } } private void AddMatchingStateMachineSuspensionPoints( ref List<KeyValuePair<SyntaxNode, SyntaxNode>>? lazyKnownMatches, ref List<SequenceEdit>? lazyRudeEdits, ImmutableArray<SyntaxNode> oldStateMachineSuspensionPoints, ImmutableArray<SyntaxNode> newStateMachineSuspensionPoints) { // State machine suspension points (yield statements, await expressions, await foreach loops, await using declarations) // determine the structure of the generated state machine. // Change of the SM structure is far more significant then changes of the value (arguments) of these nodes. // Hence we build the match such that these nodes are fixed. lazyKnownMatches ??= new List<KeyValuePair<SyntaxNode, SyntaxNode>>(); void AddMatch(ref List<KeyValuePair<SyntaxNode, SyntaxNode>> lazyKnownMatches, int oldIndex, int newIndex) { var oldNode = oldStateMachineSuspensionPoints[oldIndex]; var newNode = newStateMachineSuspensionPoints[newIndex]; if (StatementLabelEquals(oldNode, newNode)) { lazyKnownMatches.Add(KeyValuePairUtil.Create(oldNode, newNode)); } } if (oldStateMachineSuspensionPoints.Length == newStateMachineSuspensionPoints.Length) { for (var i = 0; i < oldStateMachineSuspensionPoints.Length; i++) { AddMatch(ref lazyKnownMatches, i, i); } } else { // use LCS to provide better errors (deletes, inserts and updates) var edits = GetSyntaxSequenceEdits(oldStateMachineSuspensionPoints, newStateMachineSuspensionPoints); foreach (var edit in edits) { var editKind = edit.Kind; if (editKind == EditKind.Update) { AddMatch(ref lazyKnownMatches, edit.OldIndex, edit.NewIndex); } else { lazyRudeEdits ??= new List<SequenceEdit>(); lazyRudeEdits.Add(edit); } } Debug.Assert(lazyRudeEdits != null); } } public ActiveStatementExceptionRegions GetExceptionRegions(SyntaxNode syntaxRoot, TextSpan unmappedActiveStatementSpan, bool isNonLeaf, CancellationToken cancellationToken) { var token = syntaxRoot.FindToken(unmappedActiveStatementSpan.Start); var ancestors = GetExceptionHandlingAncestors(token.Parent!, isNonLeaf); return GetExceptionRegions(ancestors, syntaxRoot.SyntaxTree, cancellationToken); } private ActiveStatementExceptionRegions GetExceptionRegions(List<SyntaxNode> exceptionHandlingAncestors, SyntaxTree tree, CancellationToken cancellationToken) { if (exceptionHandlingAncestors.Count == 0) { return new ActiveStatementExceptionRegions(ImmutableArray<SourceFileSpan>.Empty, isActiveStatementCovered: false); } var isCovered = false; using var _ = ArrayBuilder<SourceFileSpan>.GetInstance(out var result); for (var i = exceptionHandlingAncestors.Count - 1; i >= 0; i--) { var span = GetExceptionHandlingRegion(exceptionHandlingAncestors[i], out var coversAllChildren); // TODO: https://github.com/dotnet/roslyn/issues/52971 // 1) Check that the span doesn't cross #line pragmas with different file mappings. // 2) Check that the mapped path does not change and report rude edits if it does. result.Add(tree.GetMappedLineSpan(span, cancellationToken)); // Exception regions describe regions of code that can't be edited. // If the span covers all the children nodes we don't need to descend further. if (coversAllChildren) { isCovered = true; break; } } return new ActiveStatementExceptionRegions(result.ToImmutable(), isCovered); } private TextSpan GetDeletedNodeDiagnosticSpan(SyntaxNode deletedLambdaBody, Match<SyntaxNode> match, Dictionary<SyntaxNode, LambdaInfo> lambdaInfos) { var oldLambdaBody = deletedLambdaBody; while (true) { var oldParentLambdaBody = FindEnclosingLambdaBody(match.OldRoot, GetLambda(oldLambdaBody)); if (oldParentLambdaBody == null) { return GetDeletedNodeDiagnosticSpan(match.Matches, oldLambdaBody); } if (lambdaInfos.TryGetValue(oldParentLambdaBody, out var lambdaInfo) && lambdaInfo.Match != null) { return GetDeletedNodeDiagnosticSpan(lambdaInfo.Match.Matches, oldLambdaBody); } oldLambdaBody = oldParentLambdaBody; } } private TextSpan FindClosestActiveSpan(SyntaxNode statement, int statementPart) { if (TryGetActiveSpan(statement, statementPart, minLength: statement.Span.Length, out var span)) { return span; } // The node doesn't have sequence points. // E.g. "const" keyword is inserted into a local variable declaration with an initializer. foreach (var (node, part) in EnumerateNearStatements(statement)) { if (part == -1) { return node.Span; } if (TryGetActiveSpan(node, part, minLength: 0, out span)) { return span; } } // This might occur in cases where we report rude edit, so the exact location of the active span doesn't matter. // For example, when a method expression body is removed in C#. return statement.Span; } internal TextSpan GetDeletedNodeActiveSpan(IReadOnlyDictionary<SyntaxNode, SyntaxNode> forwardMap, SyntaxNode deletedNode) { foreach (var (oldNode, part) in EnumerateNearStatements(deletedNode)) { if (part == -1) { break; } if (forwardMap.TryGetValue(oldNode, out var newNode)) { return FindClosestActiveSpan(newNode, part); } } return GetDeletedNodeDiagnosticSpan(forwardMap, deletedNode); } internal TextSpan GetDeletedNodeDiagnosticSpan(IReadOnlyDictionary<SyntaxNode, SyntaxNode> forwardMap, SyntaxNode deletedNode) { var hasAncestor = TryGetMatchingAncestor(forwardMap, deletedNode, out var newAncestor); RoslynDebug.Assert(hasAncestor && newAncestor != null); return GetDiagnosticSpan(newAncestor, EditKind.Delete); } /// <summary> /// Finds the inner-most ancestor of the specified node that has a matching node in the new tree. /// </summary> private static bool TryGetMatchingAncestor(IReadOnlyDictionary<SyntaxNode, SyntaxNode> forwardMap, SyntaxNode? oldNode, [NotNullWhen(true)] out SyntaxNode? newAncestor) { while (oldNode != null) { if (forwardMap.TryGetValue(oldNode, out newAncestor)) { return true; } oldNode = oldNode.Parent; } // only happens if original oldNode is a root, // otherwise we always find a matching ancestor pair (roots). newAncestor = null; return false; } private IEnumerable<int> GetOverlappingActiveStatements(SyntaxNode declaration, ImmutableArray<UnmappedActiveStatement> statements) { var (envelope, hole) = GetActiveSpanEnvelope(declaration); if (envelope == default) { yield break; } var range = ActiveStatementsMap.GetSpansStartingInSpan( envelope.Start, envelope.End, statements, startPositionComparer: (x, y) => x.UnmappedSpan.Start.CompareTo(y)); for (var i = range.Start.Value; i < range.End.Value; i++) { if (!hole.Contains(statements[i].UnmappedSpan.Start)) { yield return i; } } } protected static bool HasParentEdit(IReadOnlyDictionary<SyntaxNode, EditKind> editMap, Edit<SyntaxNode> edit) { SyntaxNode node; switch (edit.Kind) { case EditKind.Insert: node = edit.NewNode; break; case EditKind.Delete: node = edit.OldNode; break; default: return false; } return HasEdit(editMap, node.Parent, edit.Kind); } protected static bool HasEdit(IReadOnlyDictionary<SyntaxNode, EditKind> editMap, SyntaxNode? node, EditKind editKind) { return node is object && editMap.TryGetValue(node, out var parentEdit) && parentEdit == editKind; } #endregion #region Rude Edits around Active Statement protected void AddAroundActiveStatementRudeDiagnostic(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode? oldNode, SyntaxNode? newNode, TextSpan newActiveStatementSpan) { if (oldNode == null) { RoslynDebug.Assert(newNode != null); AddRudeInsertAroundActiveStatement(diagnostics, newNode); } else if (newNode == null) { RoslynDebug.Assert(oldNode != null); AddRudeDeleteAroundActiveStatement(diagnostics, oldNode, newActiveStatementSpan); } else { AddRudeUpdateAroundActiveStatement(diagnostics, newNode); } } protected void AddRudeUpdateAroundActiveStatement(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode newNode) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.UpdateAroundActiveStatement, GetDiagnosticSpan(newNode, EditKind.Update), newNode, new[] { GetDisplayName(newNode, EditKind.Update) })); } protected void AddRudeInsertAroundActiveStatement(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode newNode) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.InsertAroundActiveStatement, GetDiagnosticSpan(newNode, EditKind.Insert), newNode, new[] { GetDisplayName(newNode, EditKind.Insert) })); } protected void AddRudeDeleteAroundActiveStatement(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldNode, TextSpan newActiveStatementSpan) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.DeleteAroundActiveStatement, newActiveStatementSpan, oldNode, new[] { GetDisplayName(oldNode, EditKind.Delete) })); } protected void ReportUnmatchedStatements<TSyntaxNode>( ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, Func<SyntaxNode, bool> nodeSelector, SyntaxNode oldActiveStatement, SyntaxNode newActiveStatement, Func<TSyntaxNode, TSyntaxNode, bool> areEquivalent, Func<TSyntaxNode, TSyntaxNode, bool>? areSimilar) where TSyntaxNode : SyntaxNode { var newNodes = GetAncestors(GetEncompassingAncestor(match.NewRoot), newActiveStatement, nodeSelector); if (newNodes == null) { return; } var oldNodes = GetAncestors(GetEncompassingAncestor(match.OldRoot), oldActiveStatement, nodeSelector); int matchCount; if (oldNodes != null) { matchCount = MatchNodes(oldNodes, newNodes, diagnostics: null, match: match, comparer: areEquivalent); // Do another pass over the nodes to improve error messages. if (areSimilar != null && matchCount < Math.Min(oldNodes.Count, newNodes.Count)) { matchCount += MatchNodes(oldNodes, newNodes, diagnostics: diagnostics, match: null, comparer: areSimilar); } } else { matchCount = 0; } if (matchCount < newNodes.Count) { ReportRudeEditsAndInserts(oldNodes, newNodes, diagnostics); } } private void ReportRudeEditsAndInserts(List<SyntaxNode?>? oldNodes, List<SyntaxNode?> newNodes, ArrayBuilder<RudeEditDiagnostic> diagnostics) { var oldNodeCount = (oldNodes != null) ? oldNodes.Count : 0; for (var i = 0; i < newNodes.Count; i++) { var newNode = newNodes[i]; if (newNode != null) { // Any difference can be expressed as insert, delete & insert, edit, or move & edit. // Heuristic: If the nesting levels of the old and new nodes are the same we report an edit. // Otherwise we report an insert. if (i < oldNodeCount && oldNodes![i] != null) { AddRudeUpdateAroundActiveStatement(diagnostics, newNode); } else { AddRudeInsertAroundActiveStatement(diagnostics, newNode); } } } } private int MatchNodes<TSyntaxNode>( List<SyntaxNode?> oldNodes, List<SyntaxNode?> newNodes, ArrayBuilder<RudeEditDiagnostic>? diagnostics, Match<SyntaxNode>? match, Func<TSyntaxNode, TSyntaxNode, bool> comparer) where TSyntaxNode : SyntaxNode { var matchCount = 0; var oldIndex = 0; for (var newIndex = 0; newIndex < newNodes.Count; newIndex++) { var newNode = newNodes[newIndex]; if (newNode == null) { continue; } SyntaxNode? oldNode; while (oldIndex < oldNodes.Count) { oldNode = oldNodes[oldIndex]; if (oldNode != null) { break; } // node has already been matched with a previous new node: oldIndex++; } if (oldIndex == oldNodes.Count) { break; } var i = -1; if (match == null) { i = IndexOfEquivalent(newNode, oldNodes, oldIndex, comparer); } else if (match.TryGetOldNode(newNode, out var partner) && comparer((TSyntaxNode)partner, (TSyntaxNode)newNode)) { i = oldNodes.IndexOf(partner, oldIndex); } if (i >= 0) { // we have an update or an exact match: oldNodes[i] = null; newNodes[newIndex] = null; matchCount++; if (diagnostics != null) { AddRudeUpdateAroundActiveStatement(diagnostics, newNode); } } } return matchCount; } private static int IndexOfEquivalent<TSyntaxNode>(SyntaxNode newNode, List<SyntaxNode?> oldNodes, int startIndex, Func<TSyntaxNode, TSyntaxNode, bool> comparer) where TSyntaxNode : SyntaxNode { for (var i = startIndex; i < oldNodes.Count; i++) { var oldNode = oldNodes[i]; if (oldNode != null && comparer((TSyntaxNode)oldNode, (TSyntaxNode)newNode)) { return i; } } return -1; } private static List<SyntaxNode?>? GetAncestors(SyntaxNode? root, SyntaxNode node, Func<SyntaxNode, bool> nodeSelector) { List<SyntaxNode?>? list = null; var current = node; while (current is object && current != root) { if (nodeSelector(current)) { list ??= new List<SyntaxNode?>(); list.Add(current); } current = current.Parent; } list?.Reverse(); return list; } #endregion #region Trivia Analysis /// <summary> /// Top-level edit script does not contain edits for a member if only trivia changed in its body. /// It also does not reflect changes in line mapping directives. /// Members that are unchanged but their location in the file changes are not considered updated. /// This method calculates line and trivia edits for all these cases. /// /// The resulting line edits are grouped by mapped document path and sorted by <see cref="SourceLineUpdate.OldLine"/> in each group. /// </summary> private void AnalyzeTrivia( Match<SyntaxNode> topMatch, IReadOnlyDictionary<SyntaxNode, EditKind> editMap, [Out] ArrayBuilder<(SyntaxNode OldNode, SyntaxNode NewNode, TextSpan DiagnosticSpan)> triviaEdits, [Out] ArrayBuilder<SequencePointUpdates> lineEdits, CancellationToken cancellationToken) { var oldTree = topMatch.OldRoot.SyntaxTree; var newTree = topMatch.NewRoot.SyntaxTree; // note: range [oldStartLine, oldEndLine] is end-inclusive using var _ = ArrayBuilder<(string filePath, int oldStartLine, int oldEndLine, int delta, SyntaxNode oldNode, SyntaxNode newNode)>.GetInstance(out var segments); foreach (var (oldNode, newNode) in topMatch.Matches) { cancellationToken.ThrowIfCancellationRequested(); if (editMap.ContainsKey(newNode)) { // Updated or inserted members will be (re)generated and don't need line edits. Debug.Assert(editMap[newNode] is EditKind.Update or EditKind.Insert); continue; } var newTokens = TryGetActiveTokens(newNode); if (newTokens == null) { continue; } // A (rude) edit could have been made that changes whether the node may contain active statements, // so although the nodes match they might not have the same active tokens. // E.g. field declaration changed to const field declaration. var oldTokens = TryGetActiveTokens(oldNode); if (oldTokens == null) { continue; } var newTokensEnum = newTokens.GetEnumerator(); var oldTokensEnum = oldTokens.GetEnumerator(); // We enumerate tokens of the body and split them into segments. // Each segment has sequence points mapped to the same file and also all lines the segment covers map to the same line delta. // The first token of a segment must be the first token that starts on the line. If the first segment token was in the middle line // the previous token on the same line would have different line delta and we wouldn't be able to map both of them at the same time. // All segments are included in the segments list regardless of their line delta (even when it's 0 - i.e. the lines did not change). // This is necessary as we need to detect collisions of multiple segments with different deltas later on. var lastNewToken = default(SyntaxToken); var lastOldStartLine = -1; var lastOldFilePath = (string?)null; var requiresUpdate = false; var firstSegmentIndex = segments.Count; var currentSegment = (path: (string?)null, oldStartLine: 0, delta: 0, firstOldNode: (SyntaxNode?)null, firstNewNode: (SyntaxNode?)null); var rudeEditSpan = default(TextSpan); // Check if the breakpoint span that covers the first node of the segment can be translated from the old to the new by adding a line delta. // If not we need to recompile the containing member since we are not able to produce line update for it. // The first node of the segment can be the first node on its line but the breakpoint span might start on the previous line. bool IsCurrentSegmentBreakpointSpanMappable() { var oldNode = currentSegment.firstOldNode; var newNode = currentSegment.firstNewNode; Contract.ThrowIfNull(oldNode); Contract.ThrowIfNull(newNode); // Some nodes (e.g. const local declaration) may not be covered by a breakpoint span. if (!TryGetEnclosingBreakpointSpan(oldNode, oldNode.SpanStart, out var oldBreakpointSpan) || !TryGetEnclosingBreakpointSpan(newNode, newNode.SpanStart, out var newBreakpointSpan)) { return true; } var oldMappedBreakpointSpan = (SourceFileSpan)oldTree.GetMappedLineSpan(oldBreakpointSpan, cancellationToken); var newMappedBreakpointSpan = (SourceFileSpan)newTree.GetMappedLineSpan(newBreakpointSpan, cancellationToken); if (oldMappedBreakpointSpan.AddLineDelta(currentSegment.delta) == newMappedBreakpointSpan) { return true; } rudeEditSpan = newBreakpointSpan; return false; } void AddCurrentSegment() { Debug.Assert(currentSegment.path != null); Debug.Assert(lastOldStartLine >= 0); // segment it ends on the line where the previous token starts (lastOldStartLine) segments.Add((currentSegment.path, currentSegment.oldStartLine, lastOldStartLine, currentSegment.delta, oldNode, newNode)); } bool oldHasToken; bool newHasToken; while (true) { oldHasToken = oldTokensEnum.MoveNext(); newHasToken = newTokensEnum.MoveNext(); // no update edit => tokens must match: Debug.Assert(oldHasToken == newHasToken); if (!oldHasToken) { if (!IsCurrentSegmentBreakpointSpanMappable()) { requiresUpdate = true; } else { // add last segment of the method body: AddCurrentSegment(); } break; } var oldSpan = oldTokensEnum.Current.Span; var newSpan = newTokensEnum.Current.Span; var oldMappedSpan = oldTree.GetMappedLineSpan(oldSpan, cancellationToken); var newMappedSpan = newTree.GetMappedLineSpan(newSpan, cancellationToken); var oldStartLine = oldMappedSpan.Span.Start.Line; var newStartLine = newMappedSpan.Span.Start.Line; var lineDelta = newStartLine - oldStartLine; // If any tokens in the method change their mapped column or mapped path the method must be recompiled // since the Debugger/SymReader does not support these updates. if (oldMappedSpan.Span.Start.Character != newMappedSpan.Span.Start.Character) { requiresUpdate = true; break; } if (currentSegment.path != oldMappedSpan.Path || currentSegment.delta != lineDelta) { // end of segment: if (currentSegment.path != null) { // Previous token start line is the same as this token start line, but the previous token line delta is not the same. // We can't therefore map the old start line to a new one using line delta since that would affect both tokens the same. if (lastOldStartLine == oldStartLine && string.Equals(lastOldFilePath, oldMappedSpan.Path)) { requiresUpdate = true; break; } if (!IsCurrentSegmentBreakpointSpanMappable()) { requiresUpdate = true; break; } // add current segment: AddCurrentSegment(); } // start new segment: currentSegment = (oldMappedSpan.Path, oldStartLine, lineDelta, oldTokensEnum.Current.Parent, newTokensEnum.Current.Parent); } lastNewToken = newTokensEnum.Current; lastOldStartLine = oldStartLine; lastOldFilePath = oldMappedSpan.Path; } // All tokens of a member body have been processed now. if (requiresUpdate) { // report the rude edit for the span of tokens that forced recompilation: if (rudeEditSpan.IsEmpty) { rudeEditSpan = TextSpan.FromBounds( lastNewToken.HasTrailingTrivia ? lastNewToken.Span.End : newTokensEnum.Current.FullSpan.Start, newTokensEnum.Current.SpanStart); } triviaEdits.Add((oldNode, newNode, rudeEditSpan)); // remove all segments added for the current member body: segments.Count = firstSegmentIndex; } } if (segments.Count == 0) { return; } // sort segments by file and then by start line: segments.Sort((x, y) => { var result = string.CompareOrdinal(x.filePath, y.filePath); return (result != 0) ? result : x.oldStartLine.CompareTo(y.oldStartLine); }); // Calculate line updates based on segments. // If two segments with different line deltas overlap we need to recompile all overlapping members except for the first one. // The debugger does not apply line deltas to recompiled methods and hence we can chose to recompile either of the overlapping segments // and apply line delta to the others. // // The line delta is applied to the start line of a sequence point. If start lines of two sequence points mapped to the same location // before the delta is applied then they will point to the same location after the delta is applied. But that wouldn't be correct // if two different mappings required applying different deltas and thus different locations. // This also applies when two methods are on the same line in the old version and they move by different deltas. using var _1 = ArrayBuilder<SourceLineUpdate>.GetInstance(out var documentLineEdits); var currentDocumentPath = segments[0].filePath; var previousOldEndLine = -1; var previousLineDelta = 0; foreach (var segment in segments) { if (segment.filePath != currentDocumentPath) { // store results for the previous document: if (documentLineEdits.Count > 0) { lineEdits.Add(new SequencePointUpdates(currentDocumentPath, documentLineEdits.ToImmutableAndClear())); } // switch to the next document: currentDocumentPath = segment.filePath; previousOldEndLine = -1; previousLineDelta = 0; } else if (segment.oldStartLine <= previousOldEndLine && segment.delta != previousLineDelta) { // The segment overlaps the previous one that has a different line delta. We need to recompile the method. // The debugger filters out line deltas that correspond to recompiled methods so we don't need to. triviaEdits.Add((segment.oldNode, segment.newNode, segment.newNode.Span)); continue; } // If the segment being added does not start on the line immediately following the previous segment end line // we need to insert another line update that resets the delta to 0 for the lines following the end line. if (documentLineEdits.Count > 0 && segment.oldStartLine > previousOldEndLine + 1) { Debug.Assert(previousOldEndLine >= 0); documentLineEdits.Add(CreateZeroDeltaSourceLineUpdate(previousOldEndLine + 1)); previousLineDelta = 0; } // Skip segment that doesn't change line numbers - the line edit would have no effect. // It was only added to facilitate detection of overlap with other segments. // Also skip the segment if the last line update has the same line delta as // consecutive same line deltas has the same effect as a single one. if (segment.delta != 0 && segment.delta != previousLineDelta) { documentLineEdits.Add(new SourceLineUpdate(segment.oldStartLine, segment.oldStartLine + segment.delta)); } previousOldEndLine = segment.oldEndLine; previousLineDelta = segment.delta; } if (currentDocumentPath != null && documentLineEdits.Count > 0) { lineEdits.Add(new SequencePointUpdates(currentDocumentPath, documentLineEdits.ToImmutable())); } } // TODO: Currently the constructor SourceLineUpdate does not allow update with zero delta. // Workaround until the debugger updates. internal static SourceLineUpdate CreateZeroDeltaSourceLineUpdate(int line) { var result = new SourceLineUpdate(); // TODO: Currently the constructor SourceLineUpdate does not allow update with zero delta. // Workaround until the debugger updates. unsafe { Unsafe.Write(&result, ((long)line << 32) | (long)line); } return result; } #endregion #region Semantic Analysis private sealed class AssemblyEqualityComparer : IEqualityComparer<IAssemblySymbol?> { public static readonly IEqualityComparer<IAssemblySymbol?> Instance = new AssemblyEqualityComparer(); public bool Equals(IAssemblySymbol? x, IAssemblySymbol? y) { // Types defined in old source assembly need to be treated as equivalent to types in the new source assembly, // provided that they only differ in their containing assemblies. // // The old source symbol has the same identity as the new one. // Two distinct assembly symbols that are referenced by the compilations have to have distinct identities. // If the compilation has two metadata references whose identities unify the compiler de-dups them and only creates // a single PE symbol. Thus comparing assemblies by identity partitions them so that each partition // contains assemblies that originated from the same Gen0 assembly. return Equals(x?.Identity, y?.Identity); } public int GetHashCode(IAssemblySymbol? obj) => obj?.Identity.GetHashCode() ?? 0; } // Ignore tuple element changes, nullability and dynamic. These type changes do not affect runtime type. // They only affect custom attributes emitted on the members - all runtimes are expected to accept // custom attribute updates in metadata deltas, even if they do not have any observable effect. private static readonly SymbolEquivalenceComparer s_runtimeSymbolEqualityComparer = new( AssemblyEqualityComparer.Instance, distinguishRefFromOut: true, tupleNamesMustMatch: false, ignoreNullableAnnotations: true); private static readonly SymbolEquivalenceComparer s_exactSymbolEqualityComparer = new( AssemblyEqualityComparer.Instance, distinguishRefFromOut: true, tupleNamesMustMatch: true, ignoreNullableAnnotations: false); protected static bool SymbolsEquivalent(ISymbol oldSymbol, ISymbol newSymbol) => s_exactSymbolEqualityComparer.Equals(oldSymbol, newSymbol); protected static bool SignaturesEquivalent(ImmutableArray<IParameterSymbol> oldParameters, ITypeSymbol oldReturnType, ImmutableArray<IParameterSymbol> newParameters, ITypeSymbol newReturnType) => ParametersEquivalent(oldParameters, newParameters, exact: false) && s_runtimeSymbolEqualityComparer.Equals(oldReturnType, newReturnType); // TODO: should check ref, ref readonly, custom mods protected static bool ParametersEquivalent(ImmutableArray<IParameterSymbol> oldParameters, ImmutableArray<IParameterSymbol> newParameters, bool exact) => oldParameters.SequenceEqual(newParameters, exact, (oldParameter, newParameter, exact) => ParameterTypesEquivalent(oldParameter, newParameter, exact)); protected static bool CustomModifiersEquivalent(CustomModifier oldModifier, CustomModifier newModifier, bool exact) => oldModifier.IsOptional == newModifier.IsOptional && TypesEquivalent(oldModifier.Modifier, newModifier.Modifier, exact); protected static bool CustomModifiersEquivalent(ImmutableArray<CustomModifier> oldModifiers, ImmutableArray<CustomModifier> newModifiers, bool exact) => oldModifiers.SequenceEqual(newModifiers, exact, (x, y, exact) => CustomModifiersEquivalent(x, y, exact)); protected static bool ReturnTypesEquivalent(IMethodSymbol oldMethod, IMethodSymbol newMethod, bool exact) => oldMethod.ReturnsByRef == newMethod.ReturnsByRef && oldMethod.ReturnsByRefReadonly == newMethod.ReturnsByRefReadonly && CustomModifiersEquivalent(oldMethod.ReturnTypeCustomModifiers, newMethod.ReturnTypeCustomModifiers, exact) && CustomModifiersEquivalent(oldMethod.RefCustomModifiers, newMethod.RefCustomModifiers, exact) && TypesEquivalent(oldMethod.ReturnType, newMethod.ReturnType, exact); protected static bool ReturnTypesEquivalent(IPropertySymbol oldProperty, IPropertySymbol newProperty, bool exact) => oldProperty.ReturnsByRef == newProperty.ReturnsByRef && oldProperty.ReturnsByRefReadonly == newProperty.ReturnsByRefReadonly && CustomModifiersEquivalent(oldProperty.TypeCustomModifiers, newProperty.TypeCustomModifiers, exact) && CustomModifiersEquivalent(oldProperty.RefCustomModifiers, newProperty.RefCustomModifiers, exact) && TypesEquivalent(oldProperty.Type, newProperty.Type, exact); protected static bool ReturnTypesEquivalent(IEventSymbol oldEvent, IEventSymbol newEvent, bool exact) => TypesEquivalent(oldEvent.Type, newEvent.Type, exact); // Note: SignatureTypeEquivalenceComparer compares dynamic and object the same. protected static bool TypesEquivalent(ITypeSymbol? oldType, ITypeSymbol? newType, bool exact) => (exact ? s_exactSymbolEqualityComparer : (IEqualityComparer<ITypeSymbol?>)s_runtimeSymbolEqualityComparer.SignatureTypeEquivalenceComparer).Equals(oldType, newType); protected static bool TypesEquivalent<T>(ImmutableArray<T> oldTypes, ImmutableArray<T> newTypes, bool exact) where T : ITypeSymbol => oldTypes.SequenceEqual(newTypes, exact, (x, y, exact) => TypesEquivalent(x, y, exact)); protected static bool ParameterTypesEquivalent(IParameterSymbol oldParameter, IParameterSymbol newParameter, bool exact) => (exact ? s_exactSymbolEqualityComparer : s_runtimeSymbolEqualityComparer).ParameterEquivalenceComparer.Equals(oldParameter, newParameter); protected static bool TypeParameterConstraintsEquivalent(ITypeParameterSymbol oldParameter, ITypeParameterSymbol newParameter, bool exact) => TypesEquivalent(oldParameter.ConstraintTypes, newParameter.ConstraintTypes, exact) && oldParameter.HasReferenceTypeConstraint == newParameter.HasReferenceTypeConstraint && oldParameter.HasValueTypeConstraint == newParameter.HasValueTypeConstraint && oldParameter.HasConstructorConstraint == newParameter.HasConstructorConstraint && oldParameter.HasNotNullConstraint == newParameter.HasNotNullConstraint && oldParameter.HasUnmanagedTypeConstraint == newParameter.HasUnmanagedTypeConstraint && oldParameter.Variance == newParameter.Variance; protected static bool TypeParametersEquivalent(ImmutableArray<ITypeParameterSymbol> oldParameters, ImmutableArray<ITypeParameterSymbol> newParameters, bool exact) => oldParameters.SequenceEqual(newParameters, exact, (oldParameter, newParameter, exact) => oldParameter.Name == newParameter.Name && TypeParameterConstraintsEquivalent(oldParameter, newParameter, exact)); protected static bool BaseTypesEquivalent(INamedTypeSymbol oldType, INamedTypeSymbol newType, bool exact) => TypesEquivalent(oldType.BaseType, newType.BaseType, exact) && TypesEquivalent(oldType.AllInterfaces, newType.AllInterfaces, exact); protected static bool MemberSignaturesEquivalent( ISymbol? oldMember, ISymbol? newMember, Func<ImmutableArray<IParameterSymbol>, ITypeSymbol, ImmutableArray<IParameterSymbol>, ITypeSymbol, bool>? signatureComparer = null) { if (oldMember == newMember) { return true; } if (oldMember == null || newMember == null || oldMember.Kind != newMember.Kind) { return false; } signatureComparer ??= SignaturesEquivalent; switch (oldMember.Kind) { case SymbolKind.Field: var oldField = (IFieldSymbol)oldMember; var newField = (IFieldSymbol)newMember; return signatureComparer(ImmutableArray<IParameterSymbol>.Empty, oldField.Type, ImmutableArray<IParameterSymbol>.Empty, newField.Type); case SymbolKind.Property: var oldProperty = (IPropertySymbol)oldMember; var newProperty = (IPropertySymbol)newMember; return signatureComparer(oldProperty.Parameters, oldProperty.Type, newProperty.Parameters, newProperty.Type); case SymbolKind.Method: var oldMethod = (IMethodSymbol)oldMember; var newMethod = (IMethodSymbol)newMember; return signatureComparer(oldMethod.Parameters, oldMethod.ReturnType, newMethod.Parameters, newMethod.ReturnType); default: throw ExceptionUtilities.UnexpectedValue(oldMember.Kind); } } private readonly struct ConstructorEdit { public readonly INamedTypeSymbol OldType; /// <summary> /// Contains syntax maps for all changed data member initializers or constructor declarations (of constructors emitting initializers) /// in the currently analyzed document. The key is the declaration of the member. /// </summary> public readonly Dictionary<SyntaxNode, Func<SyntaxNode, SyntaxNode?>?> ChangedDeclarations; public ConstructorEdit(INamedTypeSymbol oldType) { OldType = oldType; ChangedDeclarations = new Dictionary<SyntaxNode, Func<SyntaxNode, SyntaxNode?>?>(); } } private async Task<ImmutableArray<SemanticEditInfo>> AnalyzeSemanticsAsync( EditScript<SyntaxNode> editScript, IReadOnlyDictionary<SyntaxNode, EditKind> editMap, ImmutableArray<UnmappedActiveStatement> oldActiveStatements, ImmutableArray<LinePositionSpan> newActiveStatementSpans, IReadOnlyList<(SyntaxNode OldNode, SyntaxNode NewNode, TextSpan DiagnosticSpan)> triviaEdits, Project oldProject, Document? oldDocument, Document newDocument, SourceText newText, ArrayBuilder<RudeEditDiagnostic> diagnostics, ImmutableArray<ActiveStatement>.Builder newActiveStatements, ImmutableArray<ImmutableArray<SourceFileSpan>>.Builder newExceptionRegions, EditAndContinueCapabilities capabilities, bool inBreakState, CancellationToken cancellationToken) { Debug.Assert(inBreakState || newActiveStatementSpans.IsEmpty); if (editScript.Edits.Length == 0 && triviaEdits.Count == 0) { return ImmutableArray<SemanticEditInfo>.Empty; } // { new type -> constructor update } PooledDictionary<INamedTypeSymbol, ConstructorEdit>? instanceConstructorEdits = null; PooledDictionary<INamedTypeSymbol, ConstructorEdit>? staticConstructorEdits = null; var oldModel = (oldDocument != null) ? await oldDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false) : null; var newModel = await newDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var oldCompilation = oldModel?.Compilation ?? await oldProject.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false); var newCompilation = newModel.Compilation; using var _1 = PooledHashSet<ISymbol>.GetInstance(out var processedSymbols); using var _2 = ArrayBuilder<SemanticEditInfo>.GetInstance(out var semanticEdits); try { INamedTypeSymbol? lazyLayoutAttribute = null; foreach (var edit in editScript.Edits) { cancellationToken.ThrowIfCancellationRequested(); if (edit.Kind == EditKind.Move) { // Move is either a Rude Edit and already reported in syntax analysis, or has no semantic effect. // For example, in VB we allow move from field multi-declaration. // "Dim a, b As Integer" -> "Dim a As Integer" (update) and "Dim b As Integer" (move) continue; } if (edit.Kind == EditKind.Reorder) { // Currently we don't do any semantic checks for reordering // and we don't need to report them to the compiler either. // Consider: Currently symbol ordering changes are not reflected in metadata (Reflection will report original order). // Consider: Reordering of fields is not allowed since it changes the layout of the type. // This ordering should however not matter unless the type has explicit layout so we might want to allow it. // We do not check changes to the order if they occur across multiple documents (the containing type is partial). Debug.Assert(!IsDeclarationWithInitializer(edit.OldNode) && !IsDeclarationWithInitializer(edit.NewNode)); continue; } foreach (var symbolEdits in GetSymbolEdits(edit.Kind, edit.OldNode, edit.NewNode, oldModel, newModel, editMap, cancellationToken)) { Func<SyntaxNode, SyntaxNode?>? syntaxMap; SemanticEditKind editKind; var (oldSymbol, newSymbol, syntacticEditKind) = symbolEdits; var symbol = newSymbol ?? oldSymbol; Contract.ThrowIfNull(symbol); if (!processedSymbols.Add(symbol)) { continue; } var symbolKey = SymbolKey.Create(symbol, cancellationToken); // Ignore ambiguous resolution result - it may happen if there are semantic errors in the compilation. oldSymbol ??= symbolKey.Resolve(oldCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; newSymbol ??= symbolKey.Resolve(newCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; var (oldDeclaration, newDeclaration) = GetSymbolDeclarationNodes(oldSymbol, newSymbol, edit.OldNode, edit.NewNode); // The syntax change implies an update of the associated symbol but the old/new symbol does not actually exist. // Treat the edit as Insert/Delete. This may happen e.g. when all C# global statements are removed, the first one is added or they are moved to another file. if (syntacticEditKind == EditKind.Update) { if (oldSymbol == null || oldDeclaration != null && oldDeclaration.SyntaxTree != oldModel?.SyntaxTree) { syntacticEditKind = EditKind.Insert; } else if (newSymbol == null || newDeclaration != null && newDeclaration.SyntaxTree != newModel.SyntaxTree) { syntacticEditKind = EditKind.Delete; } } if (!inBreakState) { // Delete/insert/update edit of a member of a reloadable type (including nested types) results in Replace edit of the containing type. // If a Delete edit is part of delete-insert operation (member moved to a different partial type declaration or to a different file) // skip producing Replace semantic edit for this Delete edit as one will be reported by the corresponding Insert edit. var oldContainingType = oldSymbol?.ContainingType; var newContainingType = newSymbol?.ContainingType; var containingType = newContainingType ?? oldContainingType; if (containingType != null && (syntacticEditKind != EditKind.Delete || newSymbol == null)) { var containingTypeSymbolKey = SymbolKey.Create(containingType, cancellationToken); oldContainingType ??= (INamedTypeSymbol?)containingTypeSymbolKey.Resolve(oldCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; newContainingType ??= (INamedTypeSymbol?)containingTypeSymbolKey.Resolve(newCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; if (oldContainingType != null && newContainingType != null && IsReloadable(oldContainingType)) { if (processedSymbols.Add(newContainingType)) { if (capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)) { semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Replace, containingTypeSymbolKey, syntaxMap: null, syntaxMapTree: null, IsPartialEdit(oldContainingType, newContainingType, editScript.Match.OldRoot.SyntaxTree, editScript.Match.NewRoot.SyntaxTree) ? containingTypeSymbolKey : null)); } else { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingReloadableTypeNotSupportedByRuntime, newContainingType, newDeclaration, cancellationToken); } } continue; } } var oldType = oldSymbol as INamedTypeSymbol; var newType = newSymbol as INamedTypeSymbol; // Deleting a reloadable type is a rude edit, reported the same as for non-reloadable. // Adding a reloadable type is a standard type addition (TODO: unless added to a reloadable type?). // Making reloadable attribute non-reloadable results in a new version of the type that is // not reloadable but does not update the old version in-place. if (syntacticEditKind != EditKind.Delete && oldType != null && newType != null && IsReloadable(oldType)) { if (symbol == newType || processedSymbols.Add(newType)) { if (oldType.Name != newType.Name) { // https://github.com/dotnet/roslyn/issues/54886 ReportUpdateRudeEdit(diagnostics, RudeEditKind.Renamed, newType, newDeclaration, cancellationToken); } else if (oldType.Arity != newType.Arity) { // https://github.com/dotnet/roslyn/issues/54881 ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingTypeParameters, newType, newDeclaration, cancellationToken); } else if (!capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingReloadableTypeNotSupportedByRuntime, newType, newDeclaration, cancellationToken); } else { semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Replace, symbolKey, syntaxMap: null, syntaxMapTree: null, IsPartialEdit(oldType, newType, editScript.Match.OldRoot.SyntaxTree, editScript.Match.NewRoot.SyntaxTree) ? symbolKey : null)); } } continue; } } switch (syntacticEditKind) { case EditKind.Delete: { Contract.ThrowIfNull(oldModel); Contract.ThrowIfNull(oldSymbol); Contract.ThrowIfNull(oldDeclaration); var activeStatementIndices = GetOverlappingActiveStatements(oldDeclaration, oldActiveStatements); var hasActiveStatement = activeStatementIndices.Any(); // TODO: if the member isn't a field/property we should return empty span. // We need to adjust the tracking span design and UpdateUneditedSpans to account for such empty spans. if (hasActiveStatement) { var newSpan = IsDeclarationWithInitializer(oldDeclaration) ? GetDeletedNodeActiveSpan(editScript.Match.Matches, oldDeclaration) : GetDeletedNodeDiagnosticSpan(editScript.Match.Matches, oldDeclaration); foreach (var index in activeStatementIndices) { Debug.Assert(newActiveStatements[index] is null); newActiveStatements[index] = GetActiveStatementWithSpan(oldActiveStatements[index], editScript.Match.NewRoot.SyntaxTree, newSpan, diagnostics, cancellationToken); newExceptionRegions[index] = ImmutableArray<SourceFileSpan>.Empty; } } syntaxMap = null; editKind = SemanticEditKind.Delete; // Check if the declaration has been moved from one document to another. if (newSymbol != null && !(newSymbol is IMethodSymbol newMethod && newMethod.IsPartialDefinition)) { // Symbol has actually not been deleted but rather moved to another document, another partial type declaration // or replaced with an implicitly generated one (e.g. parameterless constructor, auto-generated record methods, etc.) // Report rude edit if the deleted code contains active statements. // TODO (https://github.com/dotnet/roslyn/issues/51177): // Only report rude edit when replacing member with an implicit one if it has an active statement. // We might be able to support moving active members but we would need to // 1) Move AnalyzeChangedMemberBody from Insert to Delete // 2) Handle active statements that moved to a different document in ActiveStatementTrackingService // 3) The debugger's ManagedActiveStatementUpdate might need another field indicating the source file path. if (hasActiveStatement) { ReportDeletedMemberRudeEdit(diagnostics, oldSymbol, newCompilation, RudeEditKind.DeleteActiveStatement, cancellationToken); continue; } if (!newSymbol.IsImplicitlyDeclared) { // Ignore the delete. The new symbol is explicitly declared and thus there will be an insert edit that will issue a semantic update. // Note that this could also be the case for deleting properties of records, but they will be handled when we see // their accessors below. continue; } if (IsPropertyAccessorDeclarationMatchingPrimaryConstructorParameter(oldDeclaration, newSymbol.ContainingType, out var isFirst)) { // Defer a constructor edit to cover the property initializer changing DeferConstructorEdit(oldSymbol.ContainingType, newSymbol.ContainingType, newDeclaration: null, syntaxMap, oldSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); // If there was no body deleted then we are done since the compiler generated property also has no body if (TryGetDeclarationBody(oldDeclaration) is null) { continue; } // If there was a body, then the backing field of the property will be affected so we // need to issue edits for the synthezied members. // We only need to do this once though. if (isFirst) { AddEditsForSynthesizedRecordMembers(newCompilation, newSymbol.ContainingType, semanticEdits, cancellationToken); } } // If a constructor is deleted and replaced by an implicit one the update needs to aggregate updates to all data member initializers, // or if a property is deleted that is part of a records primary constructor, which is effectivelly moving from an explicit to implicit // initializer. if (IsConstructorWithMemberInitializers(oldDeclaration)) { processedSymbols.Remove(oldSymbol); DeferConstructorEdit(oldSymbol.ContainingType, newSymbol.ContainingType, newDeclaration: null, syntaxMap, oldSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); continue; } // there is no insert edit for an implicit declaration, therefore we need to issue an update: editKind = SemanticEditKind.Update; } else { var diagnosticSpan = GetDeletedNodeDiagnosticSpan(editScript.Match.Matches, oldDeclaration); // If we got here for a global statement then the actual edit is a delete of the synthesized Main method if (IsGlobalMain(oldSymbol)) { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.Delete, diagnosticSpan, edit.OldNode, new[] { GetDisplayName(edit.OldNode, EditKind.Delete) })); continue; } // If the associated member declaration (accessor -> property/indexer/event, parameter -> method) has also been deleted skip // the delete of the symbol as it will be deleted by the delete of the associated member. // // Associated member declarations must be in the same document as the symbol, so we don't need to resolve their symbol. // In some cases the symbol even can't be resolved unambiguously. Consider e.g. resolving a method with its parameter deleted - // we wouldn't know which overload to resolve to. if (TryGetAssociatedMemberDeclaration(oldDeclaration, out var oldAssociatedMemberDeclaration)) { if (HasEdit(editMap, oldAssociatedMemberDeclaration, EditKind.Delete)) { continue; } } else if (oldSymbol.ContainingType != null) { // Check if the symbol being deleted is a member of a type that's also being deleted. // If so, skip the member deletion and only report the containing symbol deletion. var containingSymbolKey = SymbolKey.Create(oldSymbol.ContainingType, cancellationToken); var newContainingSymbol = containingSymbolKey.Resolve(newCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; if (newContainingSymbol == null) { continue; } } // deleting symbol is not allowed diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.Delete, diagnosticSpan, oldDeclaration, new[] { string.Format(FeaturesResources.member_kind_and_name, GetDisplayName(oldDeclaration, EditKind.Delete), oldSymbol.ToDisplayString(diagnosticSpan.IsEmpty ? s_fullyQualifiedMemberDisplayFormat : s_unqualifiedMemberDisplayFormat)) })); continue; } } break; case EditKind.Insert: { Contract.ThrowIfNull(newModel); Contract.ThrowIfNull(newSymbol); Contract.ThrowIfNull(newDeclaration); syntaxMap = null; editKind = SemanticEditKind.Insert; INamedTypeSymbol? oldContainingType; var newContainingType = newSymbol.ContainingType; // Check if the declaration has been moved from one document to another. if (oldSymbol != null) { // Symbol has actually not been inserted but rather moved between documents or partial type declarations, // or is replacing an implicitly generated one (e.g. parameterless constructor, auto-generated record methods, etc.) oldContainingType = oldSymbol.ContainingType; if (oldSymbol.IsImplicitlyDeclared) { // If a user explicitly implements a member of a record then we want to issue an update, not an insert. if (oldSymbol.DeclaringSyntaxReferences.Length == 1) { Contract.ThrowIfNull(oldDeclaration); ReportDeclarationInsertDeleteRudeEdits(diagnostics, oldDeclaration, newDeclaration, oldSymbol, newSymbol, cancellationToken); if (IsPropertyAccessorDeclarationMatchingPrimaryConstructorParameter(newDeclaration, newContainingType, out var isFirst)) { // If there is no body declared we can skip it entirely because for a property accessor // it matches what the compiler would have previously implicitly implemented. if (TryGetDeclarationBody(newDeclaration) is null) { continue; } // If there was a body, then the backing field of the property will be affected so we // need to issue edits for the synthezied members. Only need to do it once. if (isFirst) { AddEditsForSynthesizedRecordMembers(newCompilation, newContainingType, semanticEdits, cancellationToken); } } editKind = SemanticEditKind.Update; } } else if (oldSymbol.DeclaringSyntaxReferences.Length == 1 && newSymbol.DeclaringSyntaxReferences.Length == 1) { Contract.ThrowIfNull(oldDeclaration); // Handles partial methods and explicitly implemented properties that implement positional parameters of records // We ignore partial method definition parts when processing edits (GetSymbolForEdit). // The only declaration in compilation without syntax errors that can have multiple declaring references is a type declaration. // We can therefore ignore any symbols that have more than one declaration. ReportTypeLayoutUpdateRudeEdits(diagnostics, newSymbol, newDeclaration, newModel, ref lazyLayoutAttribute); // Compare the old declaration syntax of the symbol with its new declaration and report rude edits // if it changed in any way that's not allowed. ReportDeclarationInsertDeleteRudeEdits(diagnostics, oldDeclaration, newDeclaration, oldSymbol, newSymbol, cancellationToken); var oldBody = TryGetDeclarationBody(oldDeclaration); if (oldBody != null) { // The old symbol's declaration syntax may be located in a different document than the old version of the current document. var oldSyntaxDocument = oldProject.Solution.GetRequiredDocument(oldDeclaration.SyntaxTree); var oldSyntaxModel = await oldSyntaxDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var oldSyntaxText = await oldSyntaxDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); var newBody = TryGetDeclarationBody(newDeclaration); // Skip analysis of active statements. We already report rude edit for removal of code containing // active statements in the old declaration and don't currently support moving active statements. AnalyzeChangedMemberBody( oldDeclaration, newDeclaration, oldBody, newBody, oldSyntaxModel, newModel, oldSymbol, newSymbol, newText, oldActiveStatements: ImmutableArray<UnmappedActiveStatement>.Empty, newActiveStatementSpans: ImmutableArray<LinePositionSpan>.Empty, capabilities: capabilities, newActiveStatements, newExceptionRegions, diagnostics, out syntaxMap, cancellationToken); } // If a constructor changes from including initializers to not including initializers // we don't need to aggregate syntax map from all initializers for the constructor update semantic edit. var isNewConstructorWithMemberInitializers = IsConstructorWithMemberInitializers(newDeclaration); var isDeclarationWithInitializer = IsDeclarationWithInitializer(oldDeclaration) || IsDeclarationWithInitializer(newDeclaration); var isRecordPrimaryConstructorParameter = IsRecordPrimaryConstructorParameter(oldDeclaration); if (isNewConstructorWithMemberInitializers || isDeclarationWithInitializer || isRecordPrimaryConstructorParameter) { if (isNewConstructorWithMemberInitializers) { processedSymbols.Remove(newSymbol); } if (isDeclarationWithInitializer) { AnalyzeSymbolUpdate(oldSymbol, newSymbol, edit.NewNode, newCompilation, editScript.Match, capabilities, diagnostics, semanticEdits, syntaxMap, cancellationToken); } DeferConstructorEdit(oldSymbol.ContainingType, newContainingType, newDeclaration, syntaxMap, newSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); // Don't add a separate semantic edit. // Updates of data members with initializers and constructors that emit initializers will be aggregated and added later. continue; } editKind = SemanticEditKind.Update; } else { editKind = SemanticEditKind.Update; } } else if (TryGetAssociatedMemberDeclaration(newDeclaration, out var newAssociatedMemberDeclaration) && HasEdit(editMap, newAssociatedMemberDeclaration, EditKind.Insert)) { // If the symbol is an accessor and the containing property/indexer/event declaration has also been inserted skip // the insert of the accessor as it will be inserted by the property/indexer/event. continue; } else if (newSymbol is IParameterSymbol || newSymbol is ITypeParameterSymbol) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.Insert, GetDiagnosticSpan(newDeclaration, EditKind.Insert), newDeclaration, arguments: new[] { GetDisplayName(newDeclaration, EditKind.Insert) })); continue; } else if (newContainingType != null && !IsGlobalMain(newSymbol)) { // The edit actually adds a new symbol into an existing or a new type. var containingSymbolKey = SymbolKey.Create(newContainingType, cancellationToken); oldContainingType = containingSymbolKey.Resolve(oldCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol as INamedTypeSymbol; if (oldContainingType != null && !CanAddNewMember(newSymbol, capabilities)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.InsertNotSupportedByRuntime, GetDiagnosticSpan(newDeclaration, EditKind.Insert), newDeclaration, arguments: new[] { GetDisplayName(newDeclaration, EditKind.Insert) })); } // Check rude edits for each member even if it is inserted into a new type. ReportInsertedMemberSymbolRudeEdits(diagnostics, newSymbol, newDeclaration, insertingIntoExistingContainingType: oldContainingType != null); if (oldContainingType == null) { // Insertion of a new symbol into a new type. // We'll produce a single insert edit for the entire type. continue; } // Report rude edits for changes to data member changes of a type with an explicit layout. // We disallow moving a data member of a partial type with explicit layout even when it actually does not change the layout. // We could compare the exact order of the members but the scenario is unlikely to occur. ReportTypeLayoutUpdateRudeEdits(diagnostics, newSymbol, newDeclaration, newModel, ref lazyLayoutAttribute); // If a property or field is added to a record then the implicit constructors change, // and we need to mark a number of other synthesized members as having changed. if (newSymbol is IPropertySymbol or IFieldSymbol && newContainingType.IsRecord) { DeferConstructorEdit(oldContainingType, newContainingType, newDeclaration, syntaxMap, newSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); AddEditsForSynthesizedRecordMembers(newCompilation, newContainingType, semanticEdits, cancellationToken); } } else { // adds a new top-level type, or a global statement where none existed before, which is // therefore inserting the <Program>$ type Contract.ThrowIfFalse(newSymbol is INamedTypeSymbol || IsGlobalMain(newSymbol)); if (!capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.InsertNotSupportedByRuntime, GetDiagnosticSpan(newDeclaration, EditKind.Insert), newDeclaration, arguments: new[] { GetDisplayName(newDeclaration, EditKind.Insert) })); } oldContainingType = null; ReportInsertedMemberSymbolRudeEdits(diagnostics, newSymbol, newDeclaration, insertingIntoExistingContainingType: false); } var isConstructorWithMemberInitializers = IsConstructorWithMemberInitializers(newDeclaration); if (isConstructorWithMemberInitializers || IsDeclarationWithInitializer(newDeclaration)) { Contract.ThrowIfNull(newContainingType); Contract.ThrowIfNull(oldContainingType); // TODO (bug https://github.com/dotnet/roslyn/issues/2504) if (isConstructorWithMemberInitializers && editKind == SemanticEditKind.Insert && IsPartial(newContainingType) && HasMemberInitializerContainingLambda(oldContainingType, newSymbol.IsStatic, cancellationToken)) { // rude edit: Adding a constructor to a type with a field or property initializer that contains an anonymous function diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, GetDiagnosticSpan(newDeclaration, EditKind.Insert))); break; } DeferConstructorEdit(oldContainingType, newContainingType, newDeclaration, syntaxMap, newSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); if (isConstructorWithMemberInitializers) { processedSymbols.Remove(newSymbol); } if (isConstructorWithMemberInitializers || editKind == SemanticEditKind.Update) { // Don't add a separate semantic edit. // Edits of data members with initializers and constructors that emit initializers will be aggregated and added later. continue; } // A semantic edit to create the field/property is gonna be added. Contract.ThrowIfFalse(editKind == SemanticEditKind.Insert); } } break; case EditKind.Update: { Contract.ThrowIfNull(oldModel); Contract.ThrowIfNull(newModel); Contract.ThrowIfNull(oldSymbol); Contract.ThrowIfNull(newSymbol); editKind = SemanticEditKind.Update; syntaxMap = null; // Partial type declarations and their type parameters. if (oldSymbol.DeclaringSyntaxReferences.Length != 1 && newSymbol.DeclaringSyntaxReferences.Length != 1) { break; } Contract.ThrowIfNull(oldDeclaration); Contract.ThrowIfNull(newDeclaration); var oldBody = TryGetDeclarationBody(oldDeclaration); if (oldBody != null) { var newBody = TryGetDeclarationBody(newDeclaration); AnalyzeChangedMemberBody( oldDeclaration, newDeclaration, oldBody, newBody, oldModel, newModel, oldSymbol, newSymbol, newText, oldActiveStatements, newActiveStatementSpans, capabilities, newActiveStatements, newExceptionRegions, diagnostics, out syntaxMap, cancellationToken); } // If a constructor changes from including initializers to not including initializers // we don't need to aggregate syntax map from all initializers for the constructor update semantic edit. var isConstructorWithMemberInitializers = IsConstructorWithMemberInitializers(newDeclaration); var isDeclarationWithInitializer = IsDeclarationWithInitializer(oldDeclaration) || IsDeclarationWithInitializer(newDeclaration); if (isConstructorWithMemberInitializers || isDeclarationWithInitializer) { if (isConstructorWithMemberInitializers) { processedSymbols.Remove(newSymbol); } if (isDeclarationWithInitializer) { AnalyzeSymbolUpdate(oldSymbol, newSymbol, edit.NewNode, newCompilation, editScript.Match, capabilities, diagnostics, semanticEdits, syntaxMap, cancellationToken); } DeferConstructorEdit(oldSymbol.ContainingType, newSymbol.ContainingType, newDeclaration, syntaxMap, newSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); // Don't add a separate semantic edit. // Updates of data members with initializers and constructors that emit initializers will be aggregated and added later. continue; } } break; default: throw ExceptionUtilities.UnexpectedValue(edit.Kind); } Contract.ThrowIfFalse(editKind is SemanticEditKind.Update or SemanticEditKind.Insert); if (editKind == SemanticEditKind.Update) { Contract.ThrowIfNull(oldSymbol); AnalyzeSymbolUpdate(oldSymbol, newSymbol, edit.NewNode, newCompilation, editScript.Match, capabilities, diagnostics, semanticEdits, syntaxMap, cancellationToken); if (newSymbol is INamedTypeSymbol or IFieldSymbol or IPropertySymbol or IEventSymbol or IParameterSymbol or ITypeParameterSymbol) { continue; } } semanticEdits.Add(new SemanticEditInfo(editKind, symbolKey, syntaxMap, syntaxMapTree: null, IsPartialEdit(oldSymbol, newSymbol, editScript.Match.OldRoot.SyntaxTree, editScript.Match.NewRoot.SyntaxTree) ? symbolKey : null)); } } foreach (var (oldEditNode, newEditNode, diagnosticSpan) in triviaEdits) { Contract.ThrowIfNull(oldModel); Contract.ThrowIfNull(newModel); foreach (var (oldSymbol, newSymbol, editKind) in GetSymbolEdits(EditKind.Update, oldEditNode, newEditNode, oldModel, newModel, editMap, cancellationToken)) { // Trivia edits are only calculated for member bodies and each member has a symbol. Contract.ThrowIfNull(newSymbol); Contract.ThrowIfNull(oldSymbol); if (!processedSymbols.Add(newSymbol)) { // symbol already processed continue; } var (oldDeclaration, newDeclaration) = GetSymbolDeclarationNodes(oldSymbol, newSymbol, oldEditNode, newEditNode); Contract.ThrowIfNull(oldDeclaration); Contract.ThrowIfNull(newDeclaration); var oldContainingType = oldSymbol.ContainingType; var newContainingType = newSymbol.ContainingType; Contract.ThrowIfNull(oldContainingType); Contract.ThrowIfNull(newContainingType); if (IsReloadable(oldContainingType)) { if (processedSymbols.Add(newContainingType)) { if (capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)) { var containingTypeSymbolKey = SymbolKey.Create(oldContainingType, cancellationToken); semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Replace, containingTypeSymbolKey, syntaxMap: null, syntaxMapTree: null, IsPartialEdit(oldContainingType, newContainingType, editScript.Match.OldRoot.SyntaxTree, editScript.Match.NewRoot.SyntaxTree) ? containingTypeSymbolKey : null)); } else { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingReloadableTypeNotSupportedByRuntime, newContainingType, newDeclaration, cancellationToken); } } continue; } // We need to provide syntax map to the compiler if the member is active (see member update above): var isActiveMember = GetOverlappingActiveStatements(oldDeclaration, oldActiveStatements).Any() || IsStateMachineMethod(oldDeclaration) || ContainsLambda(oldDeclaration); var syntaxMap = isActiveMember ? CreateSyntaxMapForEquivalentNodes(oldDeclaration, newDeclaration) : null; // only trivia changed: Contract.ThrowIfFalse(IsConstructorWithMemberInitializers(oldDeclaration) == IsConstructorWithMemberInitializers(newDeclaration)); Contract.ThrowIfFalse(IsDeclarationWithInitializer(oldDeclaration) == IsDeclarationWithInitializer(newDeclaration)); var isConstructorWithMemberInitializers = IsConstructorWithMemberInitializers(newDeclaration); var isDeclarationWithInitializer = IsDeclarationWithInitializer(newDeclaration); if (isConstructorWithMemberInitializers || isDeclarationWithInitializer) { // TODO: only create syntax map if any field initializers are active/contain lambdas or this is a partial type syntaxMap ??= CreateSyntaxMapForEquivalentNodes(oldDeclaration, newDeclaration); if (isConstructorWithMemberInitializers) { processedSymbols.Remove(newSymbol); } DeferConstructorEdit(oldContainingType, newContainingType, newDeclaration, syntaxMap, newSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); // Don't add a separate semantic edit. // Updates of data members with initializers and constructors that emit initializers will be aggregated and added later. continue; } ReportMemberBodyUpdateRudeEdits(diagnostics, newDeclaration, diagnosticSpan); // updating generic methods and types if (InGenericContext(oldSymbol, out var oldIsGenericMethod)) { var rudeEdit = oldIsGenericMethod ? RudeEditKind.GenericMethodTriviaUpdate : RudeEditKind.GenericTypeTriviaUpdate; diagnostics.Add(new RudeEditDiagnostic(rudeEdit, diagnosticSpan, newEditNode, new[] { GetDisplayName(newEditNode) })); continue; } var symbolKey = SymbolKey.Create(newSymbol, cancellationToken); semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, symbolKey, syntaxMap, syntaxMapTree: null, IsPartialEdit(oldSymbol, newSymbol, editScript.Match.OldRoot.SyntaxTree, editScript.Match.NewRoot.SyntaxTree) ? symbolKey : null)); } } if (instanceConstructorEdits != null) { AddConstructorEdits( instanceConstructorEdits, editScript.Match, oldModel, oldCompilation, newCompilation, processedSymbols, capabilities, isStatic: false, semanticEdits, diagnostics, cancellationToken); } if (staticConstructorEdits != null) { AddConstructorEdits( staticConstructorEdits, editScript.Match, oldModel, oldCompilation, newCompilation, processedSymbols, capabilities, isStatic: true, semanticEdits, diagnostics, cancellationToken); } } finally { instanceConstructorEdits?.Free(); staticConstructorEdits?.Free(); } return semanticEdits.Distinct(SemanticEditInfoComparer.Instance).ToImmutableArray(); // If the symbol has a single declaring reference use its syntax node for further analysis. // Some syntax edits may not be directly associated with the declarations. // For example, in VB an update to AsNew clause of a multi-variable field declaration results in update to multiple symbols associated // with the variable declaration. But we need to analyse each symbol's modified identifier separately. (SyntaxNode? oldDeclaration, SyntaxNode? newDeclaration) GetSymbolDeclarationNodes(ISymbol? oldSymbol, ISymbol? newSymbol, SyntaxNode? oldNode, SyntaxNode? newNode) { return ( (oldSymbol != null && oldSymbol.DeclaringSyntaxReferences.Length == 1) ? GetSymbolDeclarationSyntax(oldSymbol.DeclaringSyntaxReferences.Single(), cancellationToken) : oldNode, (newSymbol != null && newSymbol.DeclaringSyntaxReferences.Length == 1) ? GetSymbolDeclarationSyntax(newSymbol.DeclaringSyntaxReferences.Single(), cancellationToken) : newNode); } } private static bool IsReloadable(INamedTypeSymbol type) { var current = type; while (current != null) { foreach (var attributeData in current.GetAttributes()) { // We assume that the attribute System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute, if it exists, is well formed. // If not an error will be reported during EnC delta emit. if (attributeData.AttributeClass is { Name: CreateNewOnMetadataUpdateAttributeName, ContainingNamespace: { Name: "CompilerServices", ContainingNamespace: { Name: "Runtime", ContainingNamespace: { Name: "System" } } } }) { return true; } } current = current.BaseType; } return false; } private sealed class SemanticEditInfoComparer : IEqualityComparer<SemanticEditInfo> { public static SemanticEditInfoComparer Instance = new(); private static readonly IEqualityComparer<SymbolKey> s_symbolKeyComparer = SymbolKey.GetComparer(); public bool Equals([AllowNull] SemanticEditInfo x, [AllowNull] SemanticEditInfo y) => s_symbolKeyComparer.Equals(x.Symbol, y.Symbol); public int GetHashCode([DisallowNull] SemanticEditInfo obj) => obj.Symbol.GetHashCode(); } private void ReportUpdatedSymbolDeclarationRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol oldSymbol, ISymbol newSymbol, SyntaxNode? newNode, Compilation newCompilation, out bool hasGeneratedAttributeChange, out bool hasGeneratedReturnTypeAttributeChange, CancellationToken cancellationToken) { var rudeEdit = RudeEditKind.None; hasGeneratedAttributeChange = false; hasGeneratedReturnTypeAttributeChange = false; if (oldSymbol.Kind != newSymbol.Kind) { rudeEdit = (oldSymbol.Kind == SymbolKind.Field || newSymbol.Kind == SymbolKind.Field) ? RudeEditKind.FieldKindUpdate : RudeEditKind.Update; } else if (oldSymbol.Name != newSymbol.Name) { rudeEdit = RudeEditKind.Renamed; // specialize rude edit for accessors and conversion operators: if (oldSymbol is IMethodSymbol oldMethod && newSymbol is IMethodSymbol newMethod) { if (oldMethod.AssociatedSymbol != null && newMethod.AssociatedSymbol != null) { if (oldMethod.MethodKind != newMethod.MethodKind) { rudeEdit = RudeEditKind.AccessorKindUpdate; } else { // rude edit will be reported by the associated symbol rudeEdit = RudeEditKind.None; } } else if (oldMethod.MethodKind == MethodKind.Conversion) { rudeEdit = RudeEditKind.ModifiersUpdate; } } } if (oldSymbol.DeclaredAccessibility != newSymbol.DeclaredAccessibility) { rudeEdit = RudeEditKind.ChangingAccessibility; } if (oldSymbol.IsStatic != newSymbol.IsStatic || oldSymbol.IsVirtual != newSymbol.IsVirtual || oldSymbol.IsAbstract != newSymbol.IsAbstract || oldSymbol.IsOverride != newSymbol.IsOverride || oldSymbol.IsExtern != newSymbol.IsExtern) { // Do not report for accessors as the error will be reported on their associated symbol. if (oldSymbol is not IMethodSymbol { AssociatedSymbol: not null }) { rudeEdit = RudeEditKind.ModifiersUpdate; } } if (oldSymbol is IFieldSymbol oldField && newSymbol is IFieldSymbol newField) { if (oldField.IsConst != newField.IsConst || oldField.IsReadOnly != newField.IsReadOnly || oldField.IsVolatile != newField.IsVolatile) { rudeEdit = RudeEditKind.ModifiersUpdate; } // Report rude edit for updating const fields and values of enums. // The latter is only reported whne the enum underlying type does not change to avoid cascading rude edits. if (oldField.IsConst && newField.IsConst && !Equals(oldField.ConstantValue, newField.ConstantValue) && TypesEquivalent(oldField.ContainingType.EnumUnderlyingType, newField.ContainingType.EnumUnderlyingType, exact: false)) { rudeEdit = RudeEditKind.InitializerUpdate; } if (oldField.IsFixedSizeBuffer && newField.IsFixedSizeBuffer && !AreFixedSizeBufferSizesEqual(oldField, newField, cancellationToken)) { rudeEdit = RudeEditKind.FixedSizeFieldUpdate; } AnalyzeType(oldField.Type, newField.Type, ref rudeEdit, ref hasGeneratedAttributeChange); } else if (oldSymbol is IMethodSymbol oldMethod && newSymbol is IMethodSymbol newMethod) { if (oldMethod.IsReadOnly != newMethod.IsReadOnly) { rudeEdit = RudeEditKind.ModifiersUpdate; } if (oldMethod.IsInitOnly != newMethod.IsInitOnly) { rudeEdit = RudeEditKind.AccessorKindUpdate; } // Consider: Generalize to compare P/Invokes regardless of how they are defined (using attribute or Declare) if (oldMethod.MethodKind == MethodKind.DeclareMethod || newMethod.MethodKind == MethodKind.DeclareMethod) { var oldImportData = oldMethod.GetDllImportData(); var newImportData = newMethod.GetDllImportData(); if (oldImportData != null && newImportData != null) { // Declare method syntax can't change these. Debug.Assert(oldImportData.BestFitMapping == newImportData.BestFitMapping || oldImportData.CallingConvention == newImportData.CallingConvention || oldImportData.ExactSpelling == newImportData.ExactSpelling || oldImportData.SetLastError == newImportData.SetLastError || oldImportData.ThrowOnUnmappableCharacter == newImportData.ThrowOnUnmappableCharacter); if (oldImportData.ModuleName != newImportData.ModuleName) { rudeEdit = RudeEditKind.DeclareLibraryUpdate; } else if (oldImportData.EntryPointName != newImportData.EntryPointName) { rudeEdit = RudeEditKind.DeclareAliasUpdate; } else if (oldImportData.CharacterSet != newImportData.CharacterSet) { rudeEdit = RudeEditKind.ModifiersUpdate; } } else if (oldImportData is null != newImportData is null) { rudeEdit = RudeEditKind.ModifiersUpdate; } } // VB implements clause if (!oldMethod.ExplicitInterfaceImplementations.SequenceEqual(newMethod.ExplicitInterfaceImplementations, (x, y) => SymbolsEquivalent(x, y))) { rudeEdit = RudeEditKind.ImplementsClauseUpdate; } // VB handles clause if (!AreHandledEventsEqual(oldMethod, newMethod)) { rudeEdit = RudeEditKind.HandlesClauseUpdate; } // Check return type - do not report for accessors, their containing symbol will report the rude edits and attribute updates. if (rudeEdit == RudeEditKind.None && oldMethod.AssociatedSymbol == null && newMethod.AssociatedSymbol == null) { AnalyzeReturnType(oldMethod, newMethod, ref rudeEdit, ref hasGeneratedReturnTypeAttributeChange); } } else if (oldSymbol is INamedTypeSymbol oldType && newSymbol is INamedTypeSymbol newType) { if (oldType.TypeKind != newType.TypeKind || oldType.IsRecord != newType.IsRecord) // TODO: https://github.com/dotnet/roslyn/issues/51874 { rudeEdit = RudeEditKind.TypeKindUpdate; } else if (oldType.IsRefLikeType != newType.IsRefLikeType || oldType.IsReadOnly != newType.IsReadOnly) { rudeEdit = RudeEditKind.ModifiersUpdate; } if (rudeEdit == RudeEditKind.None) { AnalyzeBaseTypes(oldType, newType, ref rudeEdit, ref hasGeneratedAttributeChange); if (oldType.DelegateInvokeMethod != null) { Contract.ThrowIfNull(newType.DelegateInvokeMethod); AnalyzeReturnType(oldType.DelegateInvokeMethod, newType.DelegateInvokeMethod, ref rudeEdit, ref hasGeneratedReturnTypeAttributeChange); } } } else if (oldSymbol is IPropertySymbol oldProperty && newSymbol is IPropertySymbol newProperty) { AnalyzeReturnType(oldProperty, newProperty, ref rudeEdit, ref hasGeneratedReturnTypeAttributeChange); } else if (oldSymbol is IEventSymbol oldEvent && newSymbol is IEventSymbol newEvent) { // "readonly" modifier can only be applied on the event itself, not on its accessors. if (oldEvent.AddMethod != null && newEvent.AddMethod != null && oldEvent.AddMethod.IsReadOnly != newEvent.AddMethod.IsReadOnly || oldEvent.RemoveMethod != null && newEvent.RemoveMethod != null && oldEvent.RemoveMethod.IsReadOnly != newEvent.RemoveMethod.IsReadOnly) { rudeEdit = RudeEditKind.ModifiersUpdate; } else { AnalyzeReturnType(oldEvent, newEvent, ref rudeEdit, ref hasGeneratedReturnTypeAttributeChange); } } else if (oldSymbol is IParameterSymbol oldParameter && newSymbol is IParameterSymbol newParameter) { if (oldParameter.RefKind != newParameter.RefKind || oldParameter.IsParams != newParameter.IsParams || IsExtensionMethodThisParameter(oldParameter) != IsExtensionMethodThisParameter(newParameter)) { rudeEdit = RudeEditKind.ModifiersUpdate; } else if (oldParameter.HasExplicitDefaultValue != newParameter.HasExplicitDefaultValue || oldParameter.HasExplicitDefaultValue && !Equals(oldParameter.ExplicitDefaultValue, newParameter.ExplicitDefaultValue)) { rudeEdit = RudeEditKind.InitializerUpdate; } else { AnalyzeParameterType(oldParameter, newParameter, ref rudeEdit, ref hasGeneratedAttributeChange); } } else if (oldSymbol is ITypeParameterSymbol oldTypeParameter && newSymbol is ITypeParameterSymbol newTypeParameter) { AnalyzeTypeParameter(oldTypeParameter, newTypeParameter, ref rudeEdit, ref hasGeneratedAttributeChange); } // Do not report modifier update if type kind changed. if (rudeEdit == RudeEditKind.None && oldSymbol.IsSealed != newSymbol.IsSealed) { // Do not report for accessors as the error will be reported on their associated symbol. if (oldSymbol is not IMethodSymbol { AssociatedSymbol: not null }) { rudeEdit = RudeEditKind.ModifiersUpdate; } } if (rudeEdit != RudeEditKind.None) { // so we'll just use the last global statement in the file ReportUpdateRudeEdit(diagnostics, rudeEdit, oldSymbol, newSymbol, newNode, newCompilation, cancellationToken); } } private static void AnalyzeType(ITypeSymbol oldType, ITypeSymbol newType, ref RudeEditKind rudeEdit, ref bool hasGeneratedAttributeChange, RudeEditKind rudeEditKind = RudeEditKind.TypeUpdate) { if (!TypesEquivalent(oldType, newType, exact: true)) { if (TypesEquivalent(oldType, newType, exact: false)) { hasGeneratedAttributeChange = true; } else { rudeEdit = rudeEditKind; } } } private static void AnalyzeBaseTypes(INamedTypeSymbol oldType, INamedTypeSymbol newType, ref RudeEditKind rudeEdit, ref bool hasGeneratedAttributeChange) { if (oldType.EnumUnderlyingType != null && newType.EnumUnderlyingType != null) { if (!TypesEquivalent(oldType.EnumUnderlyingType, newType.EnumUnderlyingType, exact: true)) { if (TypesEquivalent(oldType.EnumUnderlyingType, newType.EnumUnderlyingType, exact: false)) { hasGeneratedAttributeChange = true; } else { rudeEdit = RudeEditKind.EnumUnderlyingTypeUpdate; } } } else if (!BaseTypesEquivalent(oldType, newType, exact: true)) { if (BaseTypesEquivalent(oldType, newType, exact: false)) { hasGeneratedAttributeChange = true; } else { rudeEdit = RudeEditKind.BaseTypeOrInterfaceUpdate; } } } private static void AnalyzeParameterType(IParameterSymbol oldParameter, IParameterSymbol newParameter, ref RudeEditKind rudeEdit, ref bool hasGeneratedAttributeChange) { if (!ParameterTypesEquivalent(oldParameter, newParameter, exact: true)) { if (ParameterTypesEquivalent(oldParameter, newParameter, exact: false)) { hasGeneratedAttributeChange = true; } else { rudeEdit = RudeEditKind.TypeUpdate; } } } private static void AnalyzeTypeParameter(ITypeParameterSymbol oldParameter, ITypeParameterSymbol newParameter, ref RudeEditKind rudeEdit, ref bool hasGeneratedAttributeChange) { if (!TypeParameterConstraintsEquivalent(oldParameter, newParameter, exact: true)) { if (TypeParameterConstraintsEquivalent(oldParameter, newParameter, exact: false)) { hasGeneratedAttributeChange = true; } else { rudeEdit = (oldParameter.Variance != newParameter.Variance) ? RudeEditKind.VarianceUpdate : RudeEditKind.ChangingConstraints; } } } private static void AnalyzeReturnType(IMethodSymbol oldMethod, IMethodSymbol newMethod, ref RudeEditKind rudeEdit, ref bool hasGeneratedReturnTypeAttributeChange) { if (!ReturnTypesEquivalent(oldMethod, newMethod, exact: true)) { if (ReturnTypesEquivalent(oldMethod, newMethod, exact: false)) { hasGeneratedReturnTypeAttributeChange = true; } else if (IsGlobalMain(oldMethod) || IsGlobalMain(newMethod)) { rudeEdit = RudeEditKind.ChangeImplicitMainReturnType; } else { rudeEdit = RudeEditKind.TypeUpdate; } } } private static void AnalyzeReturnType(IEventSymbol oldEvent, IEventSymbol newEvent, ref RudeEditKind rudeEdit, ref bool hasGeneratedReturnTypeAttributeChange) { if (!ReturnTypesEquivalent(oldEvent, newEvent, exact: true)) { if (ReturnTypesEquivalent(oldEvent, newEvent, exact: false)) { hasGeneratedReturnTypeAttributeChange = true; } else { rudeEdit = RudeEditKind.TypeUpdate; } } } private static void AnalyzeReturnType(IPropertySymbol oldProperty, IPropertySymbol newProperty, ref RudeEditKind rudeEdit, ref bool hasGeneratedReturnTypeAttributeChange) { if (!ReturnTypesEquivalent(oldProperty, newProperty, exact: true)) { if (ReturnTypesEquivalent(oldProperty, newProperty, exact: false)) { hasGeneratedReturnTypeAttributeChange = true; } else { rudeEdit = RudeEditKind.TypeUpdate; } } } private static bool IsExtensionMethodThisParameter(IParameterSymbol parameter) => parameter is { Ordinal: 0, ContainingSymbol: IMethodSymbol { IsExtensionMethod: true } }; private void AnalyzeSymbolUpdate( ISymbol oldSymbol, ISymbol newSymbol, SyntaxNode? newNode, Compilation newCompilation, Match<SyntaxNode> topMatch, EditAndContinueCapabilities capabilities, ArrayBuilder<RudeEditDiagnostic> diagnostics, ArrayBuilder<SemanticEditInfo> semanticEdits, Func<SyntaxNode, SyntaxNode?>? syntaxMap, CancellationToken cancellationToken) { // TODO: fails in VB on delegate parameter https://github.com/dotnet/roslyn/issues/53337 // Contract.ThrowIfFalse(newSymbol.IsImplicitlyDeclared == newDeclaration is null); ReportCustomAttributeRudeEdits(diagnostics, oldSymbol, newSymbol, newNode, newCompilation, capabilities, out var hasAttributeChange, out var hasReturnTypeAttributeChange, cancellationToken); ReportUpdatedSymbolDeclarationRudeEdits(diagnostics, oldSymbol, newSymbol, newNode, newCompilation, out var hasGeneratedAttributeChange, out var hasGeneratedReturnTypeAttributeChange, cancellationToken); hasAttributeChange |= hasGeneratedAttributeChange; hasReturnTypeAttributeChange |= hasGeneratedReturnTypeAttributeChange; if (hasAttributeChange || hasReturnTypeAttributeChange) { AddCustomAttributeSemanticEdits(semanticEdits, oldSymbol, newSymbol, topMatch, syntaxMap, hasAttributeChange, hasReturnTypeAttributeChange, cancellationToken); } // updating generic methods and types if (InGenericContext(oldSymbol, out var oldIsGenericMethod) || InGenericContext(newSymbol, out _)) { var rudeEdit = oldIsGenericMethod ? RudeEditKind.GenericMethodUpdate : RudeEditKind.GenericTypeUpdate; ReportUpdateRudeEdit(diagnostics, rudeEdit, newSymbol, newNode, cancellationToken); } } private static void AddCustomAttributeSemanticEdits( ArrayBuilder<SemanticEditInfo> semanticEdits, ISymbol oldSymbol, ISymbol newSymbol, Match<SyntaxNode> topMatch, Func<SyntaxNode, SyntaxNode?>? syntaxMap, bool hasAttributeChange, bool hasReturnTypeAttributeChange, CancellationToken cancellationToken) { // Most symbol types will automatically have an edit added, so we just need to handle a few if (newSymbol is INamedTypeSymbol { DelegateInvokeMethod: not null and var newDelegateInvokeMethod } newDelegateType) { if (hasAttributeChange) { semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, SymbolKey.Create(newDelegateType, cancellationToken), syntaxMap, syntaxMapTree: null, partialType: null)); } if (hasReturnTypeAttributeChange) { // attributes applied on return type of a delegate are applied to both Invoke and BeginInvoke methods semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, SymbolKey.Create(newDelegateInvokeMethod, cancellationToken), syntaxMap, syntaxMapTree: null, partialType: null)); AddDelegateBeginInvokeEdit(newDelegateType); } } else if (newSymbol is INamedTypeSymbol) { var symbolKey = SymbolKey.Create(newSymbol, cancellationToken); semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, symbolKey, syntaxMap, syntaxMapTree: null, IsPartialEdit(oldSymbol, newSymbol, topMatch.OldRoot.SyntaxTree, topMatch.NewRoot.SyntaxTree) ? symbolKey : null)); } else if (newSymbol is ITypeParameterSymbol) { var containingTypeSymbolKey = SymbolKey.Create(newSymbol.ContainingSymbol, cancellationToken); semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, containingTypeSymbolKey, syntaxMap, syntaxMapTree: null, IsPartialEdit(oldSymbol.ContainingSymbol, newSymbol.ContainingSymbol, topMatch.OldRoot.SyntaxTree, topMatch.NewRoot.SyntaxTree) ? containingTypeSymbolKey : null)); } else if (newSymbol is IFieldSymbol or IPropertySymbol or IEventSymbol) { semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, SymbolKey.Create(newSymbol, cancellationToken), syntaxMap, syntaxMapTree: null, partialType: null)); } else if (newSymbol is IParameterSymbol) { var newContainingSymbol = newSymbol.ContainingSymbol; semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, SymbolKey.Create(newContainingSymbol, cancellationToken), syntaxMap, syntaxMapTree: null, partialType: null)); // attributes applied on parameters of a delegate are applied to both Invoke and BeginInvoke methods if (newContainingSymbol.ContainingSymbol is INamedTypeSymbol { TypeKind: TypeKind.Delegate } newContainingDelegateType) { AddDelegateBeginInvokeEdit(newContainingDelegateType); } } // attribute applied on parameters or return value of a delegate are applied to both Invoke and BeginInvoke methods void AddDelegateBeginInvokeEdit(INamedTypeSymbol delegateType) { Debug.Assert(semanticEdits != null); var beginInvokeMethod = delegateType.GetMembers("BeginInvoke").FirstOrDefault(); if (beginInvokeMethod != null) { semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, SymbolKey.Create(beginInvokeMethod, cancellationToken), syntaxMap, syntaxMapTree: null, partialType: null)); } } } private void ReportCustomAttributeRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol oldSymbol, ISymbol newSymbol, SyntaxNode? newNode, Compilation newCompilation, EditAndContinueCapabilities capabilities, out bool hasAttributeChange, out bool hasReturnTypeAttributeChange, CancellationToken cancellationToken) { // This is the only case we care about whether to issue an edit or not, because this is the only case where types have their attributes checked // and types are the only things that would otherwise not have edits reported. hasAttributeChange = ReportCustomAttributeRudeEdits(diagnostics, oldSymbol.GetAttributes(), newSymbol.GetAttributes(), oldSymbol, newSymbol, newNode, newCompilation, capabilities, cancellationToken); hasReturnTypeAttributeChange = false; if (oldSymbol is IMethodSymbol oldMethod && newSymbol is IMethodSymbol newMethod) { hasReturnTypeAttributeChange |= ReportCustomAttributeRudeEdits(diagnostics, oldMethod.GetReturnTypeAttributes(), newMethod.GetReturnTypeAttributes(), oldSymbol, newSymbol, newNode, newCompilation, capabilities, cancellationToken); } else if (oldSymbol is INamedTypeSymbol { DelegateInvokeMethod: not null and var oldInvokeMethod } && newSymbol is INamedTypeSymbol { DelegateInvokeMethod: not null and var newInvokeMethod }) { hasReturnTypeAttributeChange |= ReportCustomAttributeRudeEdits(diagnostics, oldInvokeMethod.GetReturnTypeAttributes(), newInvokeMethod.GetReturnTypeAttributes(), oldSymbol, newSymbol, newNode, newCompilation, capabilities, cancellationToken); } } private bool ReportCustomAttributeRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, ImmutableArray<AttributeData>? oldAttributes, ImmutableArray<AttributeData> newAttributes, ISymbol oldSymbol, ISymbol newSymbol, SyntaxNode? newNode, Compilation newCompilation, EditAndContinueCapabilities capabilities, CancellationToken cancellationToken) { using var _ = ArrayBuilder<AttributeData>.GetInstance(out var changedAttributes); FindChangedAttributes(oldAttributes, newAttributes, changedAttributes); if (oldAttributes.HasValue) { FindChangedAttributes(newAttributes, oldAttributes.Value, changedAttributes); } if (changedAttributes.Count == 0) { return false; } // We need diagnostics reported if the runtime doesn't support changing attributes, // but even if it does, only attributes stored in the CustomAttributes table are editable if (!capabilities.HasFlag(EditAndContinueCapabilities.ChangeCustomAttributes) || changedAttributes.Any(IsNonCustomAttribute)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingAttributesNotSupportedByRuntime, oldSymbol, newSymbol, newNode, newCompilation, cancellationToken); // If the runtime doesn't support edits then pretend there weren't changes, so no edits are produced return false; } return true; static void FindChangedAttributes(ImmutableArray<AttributeData>? oldAttributes, ImmutableArray<AttributeData> newAttributes, ArrayBuilder<AttributeData> changedAttributes) { for (var i = 0; i < newAttributes.Length; i++) { var newAttribute = newAttributes[i]; var oldAttribute = FindMatch(newAttribute, oldAttributes); if (oldAttribute is null) { changedAttributes.Add(newAttribute); } } } static AttributeData? FindMatch(AttributeData attribute, ImmutableArray<AttributeData>? oldAttributes) { if (!oldAttributes.HasValue) { return null; } foreach (var match in oldAttributes.Value) { if (SymbolEquivalenceComparer.Instance.Equals(match.AttributeClass, attribute.AttributeClass)) { if (SymbolEquivalenceComparer.Instance.Equals(match.AttributeConstructor, attribute.AttributeConstructor) && match.ConstructorArguments.SequenceEqual(attribute.ConstructorArguments, TypedConstantComparer.Instance) && match.NamedArguments.SequenceEqual(attribute.NamedArguments, NamedArgumentComparer.Instance)) { return match; } } } return null; } static bool IsNonCustomAttribute(AttributeData attribute) { // TODO: Use a compiler API to get this information rather than hard coding a list: https://github.com/dotnet/roslyn/issues/53410 // This list comes from ShouldEmitAttribute in src\Compilers\CSharp\Portable\Symbols\Attributes\AttributeData.cs // and src\Compilers\VisualBasic\Portable\Symbols\Attributes\AttributeData.vb return attribute.AttributeClass?.ToNameDisplayString() switch { "System.CLSCompliantAttribute" => true, "System.Diagnostics.CodeAnalysis.AllowNullAttribute" => true, "System.Diagnostics.CodeAnalysis.DisallowNullAttribute" => true, "System.Diagnostics.CodeAnalysis.MaybeNullAttribute" => true, "System.Diagnostics.CodeAnalysis.NotNullAttribute" => true, "System.NonSerializedAttribute" => true, "System.Reflection.AssemblyAlgorithmIdAttribute" => true, "System.Reflection.AssemblyCultureAttribute" => true, "System.Reflection.AssemblyFlagsAttribute" => true, "System.Reflection.AssemblyVersionAttribute" => true, "System.Runtime.CompilerServices.DllImportAttribute" => true, // Already covered by other rude edits, but included for completeness "System.Runtime.CompilerServices.IndexerNameAttribute" => true, "System.Runtime.CompilerServices.MethodImplAttribute" => true, "System.Runtime.CompilerServices.SpecialNameAttribute" => true, "System.Runtime.CompilerServices.TypeForwardedToAttribute" => true, "System.Runtime.InteropServices.ComImportAttribute" => true, "System.Runtime.InteropServices.DefaultParameterValueAttribute" => true, "System.Runtime.InteropServices.FieldOffsetAttribute" => true, "System.Runtime.InteropServices.InAttribute" => true, "System.Runtime.InteropServices.MarshalAsAttribute" => true, "System.Runtime.InteropServices.OptionalAttribute" => true, "System.Runtime.InteropServices.OutAttribute" => true, "System.Runtime.InteropServices.PreserveSigAttribute" => true, "System.Runtime.InteropServices.StructLayoutAttribute" => true, "System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeImportAttribute" => true, "System.Security.DynamicSecurityMethodAttribute" => true, "System.SerializableAttribute" => true, not null => IsSecurityAttribute(attribute.AttributeClass), _ => false }; } static bool IsSecurityAttribute(INamedTypeSymbol namedTypeSymbol) { // Security attributes are any attribute derived from System.Security.Permissions.SecurityAttribute, directly or indirectly var symbol = namedTypeSymbol; while (symbol is not null) { if (symbol.ToNameDisplayString() == "System.Security.Permissions.SecurityAttribute") { return true; } symbol = symbol.BaseType; } return false; } } private static bool CanAddNewMember(ISymbol newSymbol, EditAndContinueCapabilities capabilities) { if (newSymbol is IMethodSymbol or IPropertySymbol) // Properties are just get_ and set_ methods { return capabilities.HasFlag(EditAndContinueCapabilities.AddMethodToExistingType); } else if (newSymbol is IFieldSymbol field) { if (field.IsStatic) { return capabilities.HasFlag(EditAndContinueCapabilities.AddStaticFieldToExistingType); } return capabilities.HasFlag(EditAndContinueCapabilities.AddInstanceFieldToExistingType); } return true; } private static void AddEditsForSynthesizedRecordMembers(Compilation compilation, INamedTypeSymbol recordType, ArrayBuilder<SemanticEditInfo> semanticEdits, CancellationToken cancellationToken) { foreach (var member in GetRecordUpdatedSynthesizedMembers(compilation, recordType)) { var symbolKey = SymbolKey.Create(member, cancellationToken); semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, symbolKey, syntaxMap: null, syntaxMapTree: null, partialType: null)); } } private static IEnumerable<ISymbol> GetRecordUpdatedSynthesizedMembers(Compilation compilation, INamedTypeSymbol record) { // All methods that are updated have well known names, and calling GetMembers(string) is // faster than enumerating. // When a new field or property is added the PrintMembers, Equals(R) and GetHashCode() methods are updated // We don't need to worry about Deconstruct because it only changes when a new positional parameter // is added, and those are rude edits (due to adding a constructor parameter). // We don't need to worry about the constructors as they are reported elsewhere. // We have to use SingleOrDefault and check IsImplicitlyDeclared because the user can provide their // own implementation of these methods, and edits to them are handled by normal processing. var result = record.GetMembers(WellKnownMemberNames.PrintMembersMethodName) .OfType<IMethodSymbol>() .SingleOrDefault(m => m.IsImplicitlyDeclared && m.Parameters.Length == 1 && SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, compilation.GetTypeByMetadataName(typeof(StringBuilder).FullName!)) && SymbolEqualityComparer.Default.Equals(m.ReturnType, compilation.GetTypeByMetadataName(typeof(bool).FullName!))); if (result is not null) { yield return result; } result = record.GetMembers(WellKnownMemberNames.ObjectEquals) .OfType<IMethodSymbol>() .SingleOrDefault(m => m.IsImplicitlyDeclared && m.Parameters.Length == 1 && SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType)); if (result is not null) { yield return result; } result = record.GetMembers(WellKnownMemberNames.ObjectGetHashCode) .OfType<IMethodSymbol>() .SingleOrDefault(m => m.IsImplicitlyDeclared && m.Parameters.Length == 0); if (result is not null) { yield return result; } } private void ReportDeletedMemberRudeEdit( ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol oldSymbol, Compilation newCompilation, RudeEditKind rudeEditKind, CancellationToken cancellationToken) { var newNode = GetDeleteRudeEditDiagnosticNode(oldSymbol, newCompilation, cancellationToken); diagnostics.Add(new RudeEditDiagnostic( rudeEditKind, GetDiagnosticSpan(newNode, EditKind.Delete), arguments: new[] { string.Format(FeaturesResources.member_kind_and_name, GetDisplayName(oldSymbol), oldSymbol.ToDisplayString(s_unqualifiedMemberDisplayFormat)) })); } private void ReportUpdateRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, RudeEditKind rudeEdit, SyntaxNode newNode) { diagnostics.Add(new RudeEditDiagnostic( rudeEdit, GetDiagnosticSpan(newNode, EditKind.Update), newNode, new[] { GetDisplayName(newNode) })); } private void ReportUpdateRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, RudeEditKind rudeEdit, ISymbol newSymbol, SyntaxNode? newNode, CancellationToken cancellationToken) { var node = newNode ?? GetRudeEditDiagnosticNode(newSymbol, cancellationToken); var span = (rudeEdit == RudeEditKind.ChangeImplicitMainReturnType) ? GetGlobalStatementDiagnosticSpan(node) : GetDiagnosticSpan(node, EditKind.Update); var arguments = rudeEdit switch { RudeEditKind.TypeKindUpdate or RudeEditKind.ChangeImplicitMainReturnType or RudeEditKind.GenericMethodUpdate or RudeEditKind.GenericTypeUpdate => Array.Empty<string>(), RudeEditKind.ChangingReloadableTypeNotSupportedByRuntime => new[] { CreateNewOnMetadataUpdateAttributeName }, _ => new[] { GetDisplayName(newSymbol) } }; diagnostics.Add(new RudeEditDiagnostic(rudeEdit, span, node, arguments)); } private void ReportUpdateRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, RudeEditKind rudeEdit, ISymbol oldSymbol, ISymbol newSymbol, SyntaxNode? newNode, Compilation newCompilation, CancellationToken cancellationToken) { if (newSymbol.IsImplicitlyDeclared) { ReportDeletedMemberRudeEdit(diagnostics, oldSymbol, newCompilation, rudeEdit, cancellationToken); } else { ReportUpdateRudeEdit(diagnostics, rudeEdit, newSymbol, newNode, cancellationToken); } } private static SyntaxNode GetRudeEditDiagnosticNode(ISymbol symbol, CancellationToken cancellationToken) { var container = symbol; while (container != null) { if (container.DeclaringSyntaxReferences.Length > 0) { return container.DeclaringSyntaxReferences[0].GetSyntax(cancellationToken); } container = container.ContainingSymbol; } throw ExceptionUtilities.Unreachable; } private static SyntaxNode GetDeleteRudeEditDiagnosticNode(ISymbol oldSymbol, Compilation newCompilation, CancellationToken cancellationToken) { var oldContainer = oldSymbol.ContainingSymbol; while (oldContainer != null) { var containerKey = SymbolKey.Create(oldContainer, cancellationToken); var newContainer = containerKey.Resolve(newCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; if (newContainer != null) { return GetRudeEditDiagnosticNode(newContainer, cancellationToken); } oldContainer = oldContainer.ContainingSymbol; } throw ExceptionUtilities.Unreachable; } #region Type Layout Update Validation internal void ReportTypeLayoutUpdateRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol newSymbol, SyntaxNode newSyntax, SemanticModel newModel, ref INamedTypeSymbol? lazyLayoutAttribute) { switch (newSymbol.Kind) { case SymbolKind.Field: if (HasExplicitOrSequentialLayout(newSymbol.ContainingType, newModel, ref lazyLayoutAttribute)) { ReportTypeLayoutUpdateRudeEdits(diagnostics, newSymbol, newSyntax); } break; case SymbolKind.Property: if (HasBackingField(newSyntax) && HasExplicitOrSequentialLayout(newSymbol.ContainingType, newModel, ref lazyLayoutAttribute)) { ReportTypeLayoutUpdateRudeEdits(diagnostics, newSymbol, newSyntax); } break; case SymbolKind.Event: if (HasBackingField((IEventSymbol)newSymbol) && HasExplicitOrSequentialLayout(newSymbol.ContainingType, newModel, ref lazyLayoutAttribute)) { ReportTypeLayoutUpdateRudeEdits(diagnostics, newSymbol, newSyntax); } break; } } private void ReportTypeLayoutUpdateRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol symbol, SyntaxNode syntax) { var intoStruct = symbol.ContainingType.TypeKind == TypeKind.Struct; diagnostics.Add(new RudeEditDiagnostic( intoStruct ? RudeEditKind.InsertIntoStruct : RudeEditKind.InsertIntoClassWithLayout, syntax.Span, syntax, new[] { GetDisplayName(syntax, EditKind.Insert), GetDisplayName(TryGetContainingTypeDeclaration(syntax)!, EditKind.Update) })); } private static bool HasBackingField(IEventSymbol @event) { #nullable disable // https://github.com/dotnet/roslyn/issues/39288 return @event.AddMethod.IsImplicitlyDeclared #nullable enable && [email protected]; } private static bool HasExplicitOrSequentialLayout( INamedTypeSymbol type, SemanticModel model, ref INamedTypeSymbol? lazyLayoutAttribute) { if (type.TypeKind == TypeKind.Struct) { return true; } if (type.TypeKind != TypeKind.Class) { return false; } // Fields can't be inserted into a class with explicit or sequential layout var attributes = type.GetAttributes(); if (attributes.Length == 0) { return false; } lazyLayoutAttribute ??= model.Compilation.GetTypeByMetadataName(typeof(StructLayoutAttribute).FullName!); if (lazyLayoutAttribute == null) { return false; } foreach (var attribute in attributes) { RoslynDebug.Assert(attribute.AttributeClass is object); if (attribute.AttributeClass.Equals(lazyLayoutAttribute) && attribute.ConstructorArguments.Length == 1) { var layoutValue = attribute.ConstructorArguments.Single().Value; return (layoutValue is int ? (int)layoutValue : layoutValue is short ? (short)layoutValue : (int)LayoutKind.Auto) != (int)LayoutKind.Auto; } } return false; } #endregion private Func<SyntaxNode, SyntaxNode?> CreateSyntaxMapForEquivalentNodes(SyntaxNode oldDeclaration, SyntaxNode newDeclaration) { return newNode => newDeclaration.FullSpan.Contains(newNode.SpanStart) ? FindDeclarationBodyPartner(newDeclaration, oldDeclaration, newNode) : null; } private static Func<SyntaxNode, SyntaxNode?> CreateSyntaxMap(IReadOnlyDictionary<SyntaxNode, SyntaxNode> reverseMap) => newNode => reverseMap.TryGetValue(newNode, out var oldNode) ? oldNode : null; private Func<SyntaxNode, SyntaxNode?>? CreateAggregateSyntaxMap( IReadOnlyDictionary<SyntaxNode, SyntaxNode> reverseTopMatches, IReadOnlyDictionary<SyntaxNode, Func<SyntaxNode, SyntaxNode?>?> changedDeclarations) { return newNode => { // containing declaration if (!TryFindMemberDeclaration(root: null, newNode, out var newDeclarations)) { return null; } foreach (var newDeclaration in newDeclarations) { // The node is in a field, property or constructor declaration that has been changed: if (changedDeclarations.TryGetValue(newDeclaration, out var syntaxMap)) { // If syntax map is not available the declaration was either // 1) updated but is not active // 2) inserted return syntaxMap?.Invoke(newNode); } // The node is in a declaration that hasn't been changed: if (reverseTopMatches.TryGetValue(newDeclaration, out var oldDeclaration)) { return FindDeclarationBodyPartner(newDeclaration, oldDeclaration, newNode); } } return null; }; } #region Constructors and Initializers /// <summary> /// Called when a body of a constructor or an initializer of a member is updated or inserted. /// </summary> private static void DeferConstructorEdit( INamedTypeSymbol oldType, INamedTypeSymbol newType, SyntaxNode? newDeclaration, Func<SyntaxNode, SyntaxNode?>? syntaxMap, bool isStatic, ref PooledDictionary<INamedTypeSymbol, ConstructorEdit>? instanceConstructorEdits, ref PooledDictionary<INamedTypeSymbol, ConstructorEdit>? staticConstructorEdits) { Dictionary<INamedTypeSymbol, ConstructorEdit> constructorEdits; if (isStatic) { constructorEdits = staticConstructorEdits ??= PooledDictionary<INamedTypeSymbol, ConstructorEdit>.GetInstance(); } else { constructorEdits = instanceConstructorEdits ??= PooledDictionary<INamedTypeSymbol, ConstructorEdit>.GetInstance(); } if (!constructorEdits.TryGetValue(newType, out var constructorEdit)) { constructorEdits.Add(newType, constructorEdit = new ConstructorEdit(oldType)); } if (newDeclaration != null && !constructorEdit.ChangedDeclarations.ContainsKey(newDeclaration)) { constructorEdit.ChangedDeclarations.Add(newDeclaration, syntaxMap); } } private void AddConstructorEdits( IReadOnlyDictionary<INamedTypeSymbol, ConstructorEdit> updatedTypes, Match<SyntaxNode> topMatch, SemanticModel? oldModel, Compilation oldCompilation, Compilation newCompilation, IReadOnlySet<ISymbol> processedSymbols, EditAndContinueCapabilities capabilities, bool isStatic, [Out] ArrayBuilder<SemanticEditInfo> semanticEdits, [Out] ArrayBuilder<RudeEditDiagnostic> diagnostics, CancellationToken cancellationToken) { var oldSyntaxTree = topMatch.OldRoot.SyntaxTree; var newSyntaxTree = topMatch.NewRoot.SyntaxTree; foreach (var (newType, updatesInCurrentDocument) in updatedTypes) { var oldType = updatesInCurrentDocument.OldType; var anyInitializerUpdatesInCurrentDocument = updatesInCurrentDocument.ChangedDeclarations.Keys.Any(IsDeclarationWithInitializer); var isPartialEdit = IsPartialEdit(oldType, newType, oldSyntaxTree, newSyntaxTree); // Create a syntax map that aggregates syntax maps of the constructor body and all initializers in this document. // Use syntax maps stored in update.ChangedDeclarations and fallback to 1:1 map for unchanged members. // // This aggregated map will be combined with similar maps capturing members declared in partial type declarations // located in other documents when the semantic edits are merged across all changed documents of the project. // // We will create an aggregate syntax map even in cases when we don't necessarily need it, // for example if none of the edited declarations are active. It's ok to have a map that we don't need. // This is simpler than detecting whether or not some of the initializers/constructors contain active statements. var aggregateSyntaxMap = CreateAggregateSyntaxMap(topMatch.ReverseMatches, updatesInCurrentDocument.ChangedDeclarations); bool? lazyOldTypeHasMemberInitializerContainingLambda = null; foreach (var newCtor in isStatic ? newType.StaticConstructors : newType.InstanceConstructors) { if (processedSymbols.Contains(newCtor)) { // we already have an edit for the new constructor continue; } var newCtorKey = SymbolKey.Create(newCtor, cancellationToken); var syntaxMapToUse = aggregateSyntaxMap; SyntaxNode? newDeclaration = null; ISymbol? oldCtor; if (!newCtor.IsImplicitlyDeclared) { // Constructors have to have a single declaration syntax, they can't be partial newDeclaration = GetSymbolDeclarationSyntax(newCtor.DeclaringSyntaxReferences.Single(), cancellationToken); // Implicit record constructors are represented by the record declaration itself. // https://github.com/dotnet/roslyn/issues/54403 var isPrimaryRecordConstructor = IsRecordDeclaration(newDeclaration); // Constructor that doesn't contain initializers had a corresponding semantic edit produced previously // or was not edited. In either case we should not produce a semantic edit for it. if (!isPrimaryRecordConstructor && !IsConstructorWithMemberInitializers(newDeclaration)) { continue; } // If no initializer updates were made in the type we only need to produce semantic edits for constructors // whose body has been updated, otherwise we need to produce edits for all constructors that include initializers. // If changes were made to initializers or constructors of a partial type in another document they will be merged // when aggregating semantic edits from all changed documents. Rude edits resulting from those changes, if any, will // be reported in the document they were made in. if (!isPrimaryRecordConstructor && !anyInitializerUpdatesInCurrentDocument && !updatesInCurrentDocument.ChangedDeclarations.ContainsKey(newDeclaration)) { continue; } // To avoid costly SymbolKey resolution we first try to match the constructor in the current document // and special case parameter-less constructor. // In the case of records, newDeclaration will point to the record declaration, take the slow path. if (!isPrimaryRecordConstructor && topMatch.TryGetOldNode(newDeclaration, out var oldDeclaration)) { Contract.ThrowIfNull(oldModel); oldCtor = oldModel.GetDeclaredSymbol(oldDeclaration, cancellationToken); Contract.ThrowIfFalse(oldCtor is IMethodSymbol { MethodKind: MethodKind.Constructor or MethodKind.StaticConstructor }); } else if (!isPrimaryRecordConstructor && newCtor.Parameters.Length == 0) { oldCtor = TryGetParameterlessConstructor(oldType, isStatic); } else { var resolution = newCtorKey.Resolve(oldCompilation, ignoreAssemblyKey: true, cancellationToken); // There may be semantic errors in the compilation that result in multiple candidates. // Pick the first candidate. oldCtor = resolution.Symbol; } if (oldCtor == null && HasMemberInitializerContainingLambda(oldType, isStatic, ref lazyOldTypeHasMemberInitializerContainingLambda, cancellationToken)) { // TODO (bug https://github.com/dotnet/roslyn/issues/2504) // rude edit: Adding a constructor to a type with a field or property initializer that contains an anonymous function diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, GetDiagnosticSpan(newDeclaration, EditKind.Insert))); continue; } // Report an error if the updated constructor's declaration is in the current document // and its body edit is disallowed (e.g. contains stackalloc). if (oldCtor != null && newDeclaration.SyntaxTree == newSyntaxTree && anyInitializerUpdatesInCurrentDocument) { // attribute rude edit to one of the modified members var firstSpan = updatesInCurrentDocument.ChangedDeclarations.Keys.Where(IsDeclarationWithInitializer).Aggregate( (min: int.MaxValue, span: default(TextSpan)), (accumulate, node) => (node.SpanStart < accumulate.min) ? (node.SpanStart, node.Span) : accumulate).span; Contract.ThrowIfTrue(firstSpan.IsEmpty); ReportMemberBodyUpdateRudeEdits(diagnostics, newDeclaration, firstSpan); } // When explicitly implementing the copy constructor of a record the parameter name must match for symbol matching to work // TODO: Remove this requirement with https://github.com/dotnet/roslyn/issues/52563 if (oldCtor != null && !isPrimaryRecordConstructor && oldCtor.DeclaringSyntaxReferences.Length == 0 && newCtor.Parameters.Length == 1 && newType.IsRecord && oldCtor.GetParameters().First().Name != newCtor.GetParameters().First().Name) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ExplicitRecordMethodParameterNamesMustMatch, GetDiagnosticSpan(newDeclaration, EditKind.Update), arguments: new[] { oldCtor.ToDisplayString(SymbolDisplayFormats.NameFormat) })); continue; } } else { if (newCtor.Parameters.Length == 1) { // New constructor is implicitly declared with a parameter, so its the copy constructor of a record Debug.Assert(oldType.IsRecord); Debug.Assert(newType.IsRecord); // We only need an edit for this if the number of properties or fields on the record has changed. Changes to // initializers, or whether the property is part of the primary constructor, will still come through this code // path because they need an edit to the other constructor, but not the copy construcor. if (oldType.GetMembers().OfType<IPropertySymbol>().Count() == newType.GetMembers().OfType<IPropertySymbol>().Count() && oldType.GetMembers().OfType<IFieldSymbol>().Count() == newType.GetMembers().OfType<IFieldSymbol>().Count()) { continue; } oldCtor = oldType.InstanceConstructors.Single(c => c.Parameters.Length == 1 && SymbolEqualityComparer.Default.Equals(c.Parameters[0].Type, c.ContainingType)); // The copy constructor does not have a syntax map syntaxMapToUse = null; // Since there is no syntax map, we don't need to handle anything special to merge them for partial types. // The easiest way to do this is just to pretend this isn't a partial edit. isPartialEdit = false; } else { // New constructor is implicitly declared so it must be parameterless. // // Instance constructor: // Its presence indicates there are no other instance constructors in the new type and therefore // there must be a single parameterless instance constructor in the old type (constructors with parameters can't be removed). // // Static constructor: // Static constructor is always parameterless and not implicitly generated if there are no static initializers. oldCtor = TryGetParameterlessConstructor(oldType, isStatic); } Contract.ThrowIfFalse(isStatic || oldCtor != null); } if (oldCtor != null) { AnalyzeSymbolUpdate(oldCtor, newCtor, newDeclaration, newCompilation, topMatch, capabilities, diagnostics, semanticEdits, syntaxMapToUse, cancellationToken); semanticEdits.Add(new SemanticEditInfo( SemanticEditKind.Update, newCtorKey, syntaxMapToUse, syntaxMapTree: isPartialEdit ? newSyntaxTree : null, partialType: isPartialEdit ? SymbolKey.Create(newType, cancellationToken) : null)); } else { semanticEdits.Add(new SemanticEditInfo( SemanticEditKind.Insert, newCtorKey, syntaxMap: null, syntaxMapTree: null, partialType: null)); } } } } private bool HasMemberInitializerContainingLambda(INamedTypeSymbol type, bool isStatic, ref bool? lazyHasMemberInitializerContainingLambda, CancellationToken cancellationToken) { if (lazyHasMemberInitializerContainingLambda == null) { // checking the old type for existing lambdas (it's ok for the new initializers to contain lambdas) lazyHasMemberInitializerContainingLambda = HasMemberInitializerContainingLambda(type, isStatic, cancellationToken); } return lazyHasMemberInitializerContainingLambda.Value; } private bool HasMemberInitializerContainingLambda(INamedTypeSymbol type, bool isStatic, CancellationToken cancellationToken) { // checking the old type for existing lambdas (it's ok for the new initializers to contain lambdas) foreach (var member in type.GetMembers()) { if (member.IsStatic == isStatic && (member.Kind == SymbolKind.Field || member.Kind == SymbolKind.Property) && member.DeclaringSyntaxReferences.Length > 0) // skip generated fields (e.g. VB auto-property backing fields) { var syntax = GetSymbolDeclarationSyntax(member.DeclaringSyntaxReferences.Single(), cancellationToken); if (IsDeclarationWithInitializer(syntax) && ContainsLambda(syntax)) { return true; } } } return false; } private static ISymbol? TryGetParameterlessConstructor(INamedTypeSymbol type, bool isStatic) { var oldCtors = isStatic ? type.StaticConstructors : type.InstanceConstructors; if (isStatic) { return type.StaticConstructors.FirstOrDefault(); } else { return type.InstanceConstructors.FirstOrDefault(m => m.Parameters.Length == 0); } } private static bool IsPartialEdit(ISymbol? oldSymbol, ISymbol? newSymbol, SyntaxTree oldSyntaxTree, SyntaxTree newSyntaxTree) { // If any of the partial declarations of the new or the old type are in another document // the edit will need to be merged with other partial edits with matching partial type static bool IsNotInDocument(SyntaxReference reference, SyntaxTree syntaxTree) => reference.SyntaxTree != syntaxTree; return oldSymbol?.Kind == SymbolKind.NamedType && oldSymbol.DeclaringSyntaxReferences.Length > 1 && oldSymbol.DeclaringSyntaxReferences.Any(IsNotInDocument, oldSyntaxTree) || newSymbol?.Kind == SymbolKind.NamedType && newSymbol.DeclaringSyntaxReferences.Length > 1 && newSymbol.DeclaringSyntaxReferences.Any(IsNotInDocument, newSyntaxTree); } #endregion #region Lambdas and Closures private void ReportLambdaAndClosureRudeEdits( SemanticModel oldModel, SyntaxNode oldMemberBody, SemanticModel newModel, SyntaxNode newMemberBody, ISymbol newMember, IReadOnlyDictionary<SyntaxNode, LambdaInfo>? matchedLambdas, BidirectionalMap<SyntaxNode> map, EditAndContinueCapabilities capabilities, ArrayBuilder<RudeEditDiagnostic> diagnostics, out bool syntaxMapRequired, CancellationToken cancellationToken) { syntaxMapRequired = false; if (matchedLambdas != null) { var anySignatureErrors = false; foreach (var (oldLambdaBody, newLambdaInfo) in matchedLambdas) { // Any unmatched lambdas would have contained an active statement and a rude edit would be reported in syntax analysis phase. // Skip the rest of lambda and closure analysis if such lambdas are present. if (newLambdaInfo.Match == null || newLambdaInfo.NewBody == null) { return; } ReportLambdaSignatureRudeEdits(diagnostics, oldModel, oldLambdaBody, newModel, newLambdaInfo.NewBody, capabilities, out var hasErrors, cancellationToken); anySignatureErrors |= hasErrors; } ArrayBuilder<SyntaxNode>? lazyNewErroneousClauses = null; foreach (var (oldQueryClause, newQueryClause) in map.Forward) { if (!QueryClauseLambdasTypeEquivalent(oldModel, oldQueryClause, newModel, newQueryClause, cancellationToken)) { lazyNewErroneousClauses ??= ArrayBuilder<SyntaxNode>.GetInstance(); lazyNewErroneousClauses.Add(newQueryClause); } } if (lazyNewErroneousClauses != null) { foreach (var newQueryClause in from clause in lazyNewErroneousClauses orderby clause.SpanStart group clause by GetContainingQueryExpression(clause) into clausesByQuery select clausesByQuery.First()) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingQueryLambdaType, GetDiagnosticSpan(newQueryClause, EditKind.Update), newQueryClause, new[] { GetDisplayName(newQueryClause, EditKind.Update) })); } lazyNewErroneousClauses.Free(); anySignatureErrors = true; } // only dig into captures if lambda signatures match if (anySignatureErrors) { return; } } using var oldLambdaBodyEnumerator = GetLambdaBodies(oldMemberBody).GetEnumerator(); using var newLambdaBodyEnumerator = GetLambdaBodies(newMemberBody).GetEnumerator(); var oldHasLambdas = oldLambdaBodyEnumerator.MoveNext(); var newHasLambdas = newLambdaBodyEnumerator.MoveNext(); // Exit early if there are no lambdas in the method to avoid expensive data flow analysis: if (!oldHasLambdas && !newHasLambdas) { return; } var oldCaptures = GetCapturedVariables(oldModel, oldMemberBody); var newCaptures = GetCapturedVariables(newModel, newMemberBody); // { new capture index -> old capture index } using var _1 = ArrayBuilder<int>.GetInstance(newCaptures.Length, fillWithValue: 0, out var reverseCapturesMap); // { new capture index -> new closure scope or null for "this" } using var _2 = ArrayBuilder<SyntaxNode?>.GetInstance(newCaptures.Length, fillWithValue: null, out var newCapturesToClosureScopes); // Can be calculated from other maps but it's simpler to just calculate it upfront. // { old capture index -> old closure scope or null for "this" } using var _3 = ArrayBuilder<SyntaxNode?>.GetInstance(oldCaptures.Length, fillWithValue: null, out var oldCapturesToClosureScopes); CalculateCapturedVariablesMaps( oldCaptures, oldMemberBody, newCaptures, newMember, newMemberBody, map, reverseCapturesMap, newCapturesToClosureScopes, oldCapturesToClosureScopes, diagnostics, out var anyCaptureErrors, cancellationToken); if (anyCaptureErrors) { return; } // Every captured variable accessed in the new lambda has to be // accessed in the old lambda as well and vice versa. // // An added lambda can only reference captured variables that // // This requirement ensures that: // - Lambda methods are generated to the same frame as before, so they can be updated in-place. // - "Parent" links between closure scopes are preserved. using var _11 = PooledDictionary<ISymbol, int>.GetInstance(out var oldCapturesIndex); using var _12 = PooledDictionary<ISymbol, int>.GetInstance(out var newCapturesIndex); BuildIndex(oldCapturesIndex, oldCaptures); BuildIndex(newCapturesIndex, newCaptures); if (matchedLambdas != null) { var mappedLambdasHaveErrors = false; foreach (var (oldLambdaBody, newLambdaInfo) in matchedLambdas) { var newLambdaBody = newLambdaInfo.NewBody; // The map now contains only matched lambdas. Any unmatched ones would have contained an active statement and // a rude edit would be reported in syntax analysis phase. RoslynDebug.Assert(newLambdaInfo.Match != null && newLambdaBody != null); var accessedOldCaptures = GetAccessedCaptures(oldLambdaBody, oldModel, oldCaptures, oldCapturesIndex); var accessedNewCaptures = GetAccessedCaptures(newLambdaBody, newModel, newCaptures, newCapturesIndex); // Requirement: // (new(ReadInside) \/ new(WrittenInside)) /\ new(Captured) == (old(ReadInside) \/ old(WrittenInside)) /\ old(Captured) for (var newCaptureIndex = 0; newCaptureIndex < newCaptures.Length; newCaptureIndex++) { var newAccessed = accessedNewCaptures[newCaptureIndex]; var oldAccessed = accessedOldCaptures[reverseCapturesMap[newCaptureIndex]]; if (newAccessed != oldAccessed) { var newCapture = newCaptures[newCaptureIndex]; var rudeEdit = newAccessed ? RudeEditKind.AccessingCapturedVariableInLambda : RudeEditKind.NotAccessingCapturedVariableInLambda; var arguments = new[] { newCapture.Name, GetDisplayName(GetLambda(newLambdaBody)) }; if (newCapture.IsThisParameter() || oldAccessed) { // changed accessed to "this", or captured variable accessed in old lambda is not accessed in the new lambda diagnostics.Add(new RudeEditDiagnostic(rudeEdit, GetDiagnosticSpan(GetLambda(newLambdaBody), EditKind.Update), null, arguments)); } else if (newAccessed) { // captured variable accessed in new lambda is not accessed in the old lambda var hasUseSites = false; foreach (var useSite in GetVariableUseSites(GetLambdaBodyExpressionsAndStatements(newLambdaBody), newCapture, newModel, cancellationToken)) { hasUseSites = true; diagnostics.Add(new RudeEditDiagnostic(rudeEdit, useSite.Span, null, arguments)); } Debug.Assert(hasUseSites); } mappedLambdasHaveErrors = true; } } } if (mappedLambdasHaveErrors) { return; } } // Report rude edits for lambdas added to the method. // We already checked that no new captures are introduced or removed. // We also need to make sure that no new parent frame links are introduced. // // We could implement the same analysis as the compiler does when rewriting lambdas - // to determine what closure scopes are connected at runtime via parent link, // and then disallow adding a lambda that connects two previously unconnected // groups of scopes. // // However even if we implemented that logic here, it would be challenging to // present the result of the analysis to the user in a short comprehensible error message. // // In practice, we believe the common scenarios are (in order of commonality): // 1) adding a static lambda // 2) adding a lambda that accesses only "this" // 3) adding a lambda that accesses variables from the same scope // 4) adding a lambda that accesses "this" and variables from a single scope // 5) adding a lambda that accesses variables from different scopes that are linked // 6) adding a lambda that accesses variables from unlinked scopes // // We currently allow #1, #2, and #3 and report a rude edit for the other cases. // In future we might be able to enable more. var containingTypeDeclaration = TryGetContainingTypeDeclaration(newMemberBody); var isInInterfaceDeclaration = containingTypeDeclaration != null && IsInterfaceDeclaration(containingTypeDeclaration); var newHasLambdaBodies = newHasLambdas; while (newHasLambdaBodies) { var (newLambda, newLambdaBody1, newLambdaBody2) = newLambdaBodyEnumerator.Current; if (!map.Reverse.ContainsKey(newLambda)) { if (!CanAddNewLambda(newLambda, capabilities, matchedLambdas)) { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.InsertNotSupportedByRuntime, GetDiagnosticSpan(newLambda, EditKind.Insert), newLambda, new string[] { GetDisplayName(newLambda, EditKind.Insert) })); } // TODO: https://github.com/dotnet/roslyn/issues/37128 // Local functions are emitted directly to the type containing the containing method. // Although local functions are non-virtual the Core CLR currently does not support adding any method to an interface. if (isInInterfaceDeclaration && IsLocalFunction(newLambda)) { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.InsertLocalFunctionIntoInterfaceMethod, GetDiagnosticSpan(newLambda, EditKind.Insert), newLambda)); } ReportMultiScopeCaptures(newLambdaBody1, newModel, newCaptures, newCaptures, newCapturesToClosureScopes, newCapturesIndex, reverseCapturesMap, diagnostics, isInsert: true, cancellationToken: cancellationToken); if (newLambdaBody2 != null) { ReportMultiScopeCaptures(newLambdaBody2, newModel, newCaptures, newCaptures, newCapturesToClosureScopes, newCapturesIndex, reverseCapturesMap, diagnostics, isInsert: true, cancellationToken: cancellationToken); } } newHasLambdaBodies = newLambdaBodyEnumerator.MoveNext(); } // Similarly for addition. We don't allow removal of lambda that has captures from multiple scopes. var oldHasMoreLambdas = oldHasLambdas; while (oldHasMoreLambdas) { var (oldLambda, oldLambdaBody1, oldLambdaBody2) = oldLambdaBodyEnumerator.Current; if (!map.Forward.ContainsKey(oldLambda)) { ReportMultiScopeCaptures(oldLambdaBody1, oldModel, oldCaptures, newCaptures, oldCapturesToClosureScopes, oldCapturesIndex, reverseCapturesMap, diagnostics, isInsert: false, cancellationToken: cancellationToken); if (oldLambdaBody2 != null) { ReportMultiScopeCaptures(oldLambdaBody2, oldModel, oldCaptures, newCaptures, oldCapturesToClosureScopes, oldCapturesIndex, reverseCapturesMap, diagnostics, isInsert: false, cancellationToken: cancellationToken); } } oldHasMoreLambdas = oldLambdaBodyEnumerator.MoveNext(); } syntaxMapRequired = newHasLambdas; } private IEnumerable<(SyntaxNode lambda, SyntaxNode lambdaBody1, SyntaxNode? lambdaBody2)> GetLambdaBodies(SyntaxNode body) { foreach (var node in body.DescendantNodesAndSelf()) { if (TryGetLambdaBodies(node, out var body1, out var body2)) { yield return (node, body1, body2); } } } private bool CanAddNewLambda(SyntaxNode newLambda, EditAndContinueCapabilities capabilities, IReadOnlyDictionary<SyntaxNode, LambdaInfo>? matchedLambdas) { // New local functions mean new methods in existing classes if (IsLocalFunction(newLambda)) { return capabilities.HasFlag(EditAndContinueCapabilities.AddMethodToExistingType); } // New lambdas sometimes mean creating new helper classes, and sometimes mean new methods in exising helper classes // Unfortunately we are limited here in what we can do here. See: https://github.com/dotnet/roslyn/issues/52759 // If there is already a lambda in the method then the new lambda would result in a new method in the existing helper class. // This check is redundant with the below, once the limitation in the referenced issue is resolved if (matchedLambdas is { Count: > 0 }) { return capabilities.HasFlag(EditAndContinueCapabilities.AddMethodToExistingType); } // If there is already a lambda in the class then the new lambda would result in a new method in the existing helper class. // If there isn't already a lambda in the class then the new lambda would result in a new helper class. // Unfortunately right now we can't determine which of these is true so we have to just check both capabilities instead. return capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition) && capabilities.HasFlag(EditAndContinueCapabilities.AddMethodToExistingType); } private void ReportMultiScopeCaptures( SyntaxNode lambdaBody, SemanticModel model, ImmutableArray<ISymbol> captures, ImmutableArray<ISymbol> newCaptures, ArrayBuilder<SyntaxNode?> newCapturesToClosureScopes, PooledDictionary<ISymbol, int> capturesIndex, ArrayBuilder<int> reverseCapturesMap, ArrayBuilder<RudeEditDiagnostic> diagnostics, bool isInsert, CancellationToken cancellationToken) { if (captures.Length == 0) { return; } var accessedCaptures = GetAccessedCaptures(lambdaBody, model, captures, capturesIndex); var firstAccessedCaptureIndex = -1; for (var i = 0; i < captures.Length; i++) { if (accessedCaptures[i]) { if (firstAccessedCaptureIndex == -1) { firstAccessedCaptureIndex = i; } else if (newCapturesToClosureScopes[firstAccessedCaptureIndex] != newCapturesToClosureScopes[i]) { // the lambda accesses variables from two different scopes: TextSpan errorSpan; RudeEditKind rudeEdit; if (isInsert) { if (captures[i].IsThisParameter()) { errorSpan = GetDiagnosticSpan(GetLambda(lambdaBody), EditKind.Insert); } else { errorSpan = GetVariableUseSites(GetLambdaBodyExpressionsAndStatements(lambdaBody), captures[i], model, cancellationToken).First().Span; } rudeEdit = RudeEditKind.InsertLambdaWithMultiScopeCapture; } else { errorSpan = newCaptures[reverseCapturesMap.IndexOf(i)].Locations.Single().SourceSpan; rudeEdit = RudeEditKind.DeleteLambdaWithMultiScopeCapture; } diagnostics.Add(new RudeEditDiagnostic( rudeEdit, errorSpan, null, new[] { GetDisplayName(GetLambda(lambdaBody)), captures[firstAccessedCaptureIndex].Name, captures[i].Name })); break; } } } } private BitVector GetAccessedCaptures(SyntaxNode lambdaBody, SemanticModel model, ImmutableArray<ISymbol> captures, PooledDictionary<ISymbol, int> capturesIndex) { var result = BitVector.Create(captures.Length); foreach (var expressionOrStatement in GetLambdaBodyExpressionsAndStatements(lambdaBody)) { var dataFlow = model.AnalyzeDataFlow(expressionOrStatement); MarkVariables(ref result, dataFlow.ReadInside, capturesIndex); MarkVariables(ref result, dataFlow.WrittenInside, capturesIndex); } return result; } private static void MarkVariables(ref BitVector mask, ImmutableArray<ISymbol> variables, Dictionary<ISymbol, int> index) { foreach (var variable in variables) { if (index.TryGetValue(variable, out var newCaptureIndex)) { mask[newCaptureIndex] = true; } } } private static void BuildIndex<TKey>(Dictionary<TKey, int> index, ImmutableArray<TKey> array) where TKey : notnull { for (var i = 0; i < array.Length; i++) { index.Add(array[i], i); } } /// <summary> /// Returns node that represents a declaration of the symbol whose <paramref name="reference"/> is passed in. /// </summary> protected abstract SyntaxNode GetSymbolDeclarationSyntax(SyntaxReference reference, CancellationToken cancellationToken); private static TextSpan GetThisParameterDiagnosticSpan(ISymbol member) => member.Locations.First().SourceSpan; private static TextSpan GetVariableDiagnosticSpan(ISymbol local) { // Note that in VB implicit value parameter in property setter doesn't have a location. // In C# its location is the location of the setter. // See https://github.com/dotnet/roslyn/issues/14273 return local.Locations.FirstOrDefault()?.SourceSpan ?? local.ContainingSymbol.Locations.First().SourceSpan; } private static (SyntaxNode? Node, int Ordinal) GetParameterKey(IParameterSymbol parameter, CancellationToken cancellationToken) { var containingLambda = parameter.ContainingSymbol as IMethodSymbol; if (containingLambda?.MethodKind is MethodKind.LambdaMethod or MethodKind.LocalFunction) { var oldContainingLambdaSyntax = containingLambda.DeclaringSyntaxReferences.Single().GetSyntax(cancellationToken); return (oldContainingLambdaSyntax, parameter.Ordinal); } else { return (Node: null, parameter.Ordinal); } } private static bool TryMapParameter((SyntaxNode? Node, int Ordinal) parameterKey, IReadOnlyDictionary<SyntaxNode, SyntaxNode> map, out (SyntaxNode? Node, int Ordinal) mappedParameterKey) { var containingLambdaSyntax = parameterKey.Node; if (containingLambdaSyntax == null) { // method parameter: no syntax, same ordinal (can't change since method signatures must match) mappedParameterKey = parameterKey; return true; } if (map.TryGetValue(containingLambdaSyntax, out var mappedContainingLambdaSyntax)) { // parameter of an existing lambda: same ordinal (can't change since lambda signatures must match), mappedParameterKey = (mappedContainingLambdaSyntax, parameterKey.Ordinal); return true; } // no mapping mappedParameterKey = default; return false; } private void CalculateCapturedVariablesMaps( ImmutableArray<ISymbol> oldCaptures, SyntaxNode oldMemberBody, ImmutableArray<ISymbol> newCaptures, ISymbol newMember, SyntaxNode newMemberBody, BidirectionalMap<SyntaxNode> map, [Out] ArrayBuilder<int> reverseCapturesMap, // {new capture index -> old capture index} [Out] ArrayBuilder<SyntaxNode?> newCapturesToClosureScopes, // {new capture index -> new closure scope} [Out] ArrayBuilder<SyntaxNode?> oldCapturesToClosureScopes, // {old capture index -> old closure scope} [Out] ArrayBuilder<RudeEditDiagnostic> diagnostics, out bool hasErrors, CancellationToken cancellationToken) { hasErrors = false; // Validate that all variables that are/were captured in the new/old body were captured in // the old/new one and their type and scope haven't changed. // // Frames are created based upon captured variables and their scopes. If the scopes haven't changed the frames won't either. // // In future we can relax some of these limitations. // - If a newly captured variable's scope is already a closure then it is ok to lift this variable to the existing closure, // unless any lambda (or the containing member) that can access the variable is active. If it was active we would need // to copy the value of the local variable to the lifted field. // // Consider the following edit: // Gen0 Gen1 // ... ... // { { // int x = 1, y = 2; int x = 1, y = 2; // F(() => x); F(() => x); // AS-->W(y) AS-->W(y) // F(() => y); // } } // ... ... // // - If an "uncaptured" variable's scope still defines other captured variables it is ok to cease capturing the variable, // unless any lambda (or the containing member) that can access the variable is active. If it was active we would need // to copy the value of the lifted field to the local variable (consider reverse edit in the example above). // // - While building the closure tree for the new version the compiler can recreate // the closure tree of the previous version and then map // closure scopes in the new version to the previous ones, keeping empty closures around. using var _1 = PooledDictionary<SyntaxNode, int>.GetInstance(out var oldLocalCapturesBySyntax); using var _2 = PooledDictionary<(SyntaxNode? Node, int Ordinal), int>.GetInstance(out var oldParameterCapturesByLambdaAndOrdinal); for (var i = 0; i < oldCaptures.Length; i++) { var oldCapture = oldCaptures[i]; if (oldCapture.Kind == SymbolKind.Parameter) { oldParameterCapturesByLambdaAndOrdinal.Add(GetParameterKey((IParameterSymbol)oldCapture, cancellationToken), i); } else { oldLocalCapturesBySyntax.Add(oldCapture.DeclaringSyntaxReferences.Single().GetSyntax(cancellationToken), i); } } for (var newCaptureIndex = 0; newCaptureIndex < newCaptures.Length; newCaptureIndex++) { var newCapture = newCaptures[newCaptureIndex]; int oldCaptureIndex; if (newCapture.Kind == SymbolKind.Parameter) { var newParameterCapture = (IParameterSymbol)newCapture; var newParameterKey = GetParameterKey(newParameterCapture, cancellationToken); if (!TryMapParameter(newParameterKey, map.Reverse, out var oldParameterKey) || !oldParameterCapturesByLambdaAndOrdinal.TryGetValue(oldParameterKey, out oldCaptureIndex)) { // parameter has not been captured prior the edit: diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.CapturingVariable, GetVariableDiagnosticSpan(newCapture), null, new[] { newCapture.Name })); hasErrors = true; continue; } // Remove the old parameter capture so that at the end we can use this hashset // to identify old captures that don't have a corresponding capture in the new version: oldParameterCapturesByLambdaAndOrdinal.Remove(oldParameterKey); } else { var newCaptureSyntax = newCapture.DeclaringSyntaxReferences.Single().GetSyntax(cancellationToken); // variable doesn't exists in the old method or has not been captured prior the edit: if (!map.Reverse.TryGetValue(newCaptureSyntax, out var mappedOldSyntax) || !oldLocalCapturesBySyntax.TryGetValue(mappedOldSyntax, out oldCaptureIndex)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.CapturingVariable, newCapture.Locations.First().SourceSpan, null, new[] { newCapture.Name })); hasErrors = true; continue; } // Remove the old capture so that at the end we can use this hashset // to identify old captures that don't have a corresponding capture in the new version: oldLocalCapturesBySyntax.Remove(mappedOldSyntax); } reverseCapturesMap[newCaptureIndex] = oldCaptureIndex; // the type and scope of parameters can't change if (newCapture.Kind == SymbolKind.Parameter) { continue; } var oldCapture = oldCaptures[oldCaptureIndex]; // Parameter capture can't be changed to local capture and vice versa // because parameters can't be introduced or deleted during EnC // (we checked above for changes in lambda signatures). // Also range variables can't be mapped to other variables since they have // different kinds of declarator syntax nodes. Debug.Assert(oldCapture.Kind == newCapture.Kind); // Range variables don't have types. Each transparent identifier (range variable use) // might have a different type. Changing these types is ok as long as the containing lambda // signatures remain unchanged, which we validate for all lambdas in general. // // The scope of a transparent identifier is the containing lambda body. Since we verify that // each lambda body accesses the same captured variables (including range variables) // the corresponding scopes are guaranteed to be preserved as well. if (oldCapture.Kind == SymbolKind.RangeVariable) { continue; } // rename: // Note that the name has to match exactly even in VB, since we can't rename a field. // Consider: We could allow rename by emitting some special debug info for the field. if (newCapture.Name != oldCapture.Name) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.RenamingCapturedVariable, newCapture.Locations.First().SourceSpan, null, new[] { oldCapture.Name, newCapture.Name })); hasErrors = true; continue; } // type check var oldTypeOpt = GetType(oldCapture); var newTypeOpt = GetType(newCapture); if (!TypesEquivalent(oldTypeOpt, newTypeOpt, exact: false)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingCapturedVariableType, GetVariableDiagnosticSpan(newCapture), null, new[] { newCapture.Name, oldTypeOpt.ToDisplayString(ErrorDisplayFormat) })); hasErrors = true; continue; } // scope check: var oldScopeOpt = GetCapturedVariableScope(oldCapture, oldMemberBody, cancellationToken); var newScopeOpt = GetCapturedVariableScope(newCapture, newMemberBody, cancellationToken); if (!AreEquivalentClosureScopes(oldScopeOpt, newScopeOpt, map.Reverse)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingCapturedVariableScope, GetVariableDiagnosticSpan(newCapture), null, new[] { newCapture.Name })); hasErrors = true; continue; } newCapturesToClosureScopes[newCaptureIndex] = newScopeOpt; oldCapturesToClosureScopes[oldCaptureIndex] = oldScopeOpt; } // What's left in oldCapturesBySyntax are captured variables in the previous version // that have no corresponding captured variables in the new version. // Report a rude edit for all such variables. if (oldParameterCapturesByLambdaAndOrdinal.Count > 0) { // syntax-less parameters are not included: var newMemberParametersWithSyntax = newMember.GetParameters(); // uncaptured parameters: foreach (var ((oldContainingLambdaSyntax, ordinal), oldCaptureIndex) in oldParameterCapturesByLambdaAndOrdinal) { var oldCapture = oldCaptures[oldCaptureIndex]; TextSpan span; if (ordinal < 0) { // this parameter: span = GetThisParameterDiagnosticSpan(newMember); } else if (oldContainingLambdaSyntax != null) { // lambda: span = GetLambdaParameterDiagnosticSpan(oldContainingLambdaSyntax, ordinal); } else if (oldCapture.IsImplicitValueParameter()) { // value parameter of a property/indexer setter, event adder/remover: span = newMember.Locations.First().SourceSpan; } else { // method or property: span = GetVariableDiagnosticSpan(newMemberParametersWithSyntax[ordinal]); } diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.NotCapturingVariable, span, null, new[] { oldCapture.Name })); } hasErrors = true; } if (oldLocalCapturesBySyntax.Count > 0) { // uncaptured or deleted variables: foreach (var entry in oldLocalCapturesBySyntax) { var oldCaptureNode = entry.Key; var oldCaptureIndex = entry.Value; var name = oldCaptures[oldCaptureIndex].Name; if (map.Forward.TryGetValue(oldCaptureNode, out var newCaptureNode)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.NotCapturingVariable, newCaptureNode.Span, null, new[] { name })); } else { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.DeletingCapturedVariable, GetDeletedNodeDiagnosticSpan(map.Forward, oldCaptureNode), null, new[] { name })); } } hasErrors = true; } } private void ReportLambdaSignatureRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, SemanticModel oldModel, SyntaxNode oldLambdaBody, SemanticModel newModel, SyntaxNode newLambdaBody, EditAndContinueCapabilities capabilities, out bool hasSignatureErrors, CancellationToken cancellationToken) { hasSignatureErrors = false; var newLambda = GetLambda(newLambdaBody); var oldLambda = GetLambda(oldLambdaBody); Debug.Assert(IsNestedFunction(newLambda) == IsNestedFunction(oldLambda)); // queries are analyzed separately if (!IsNestedFunction(newLambda)) { return; } if (IsLocalFunction(oldLambda) != IsLocalFunction(newLambda)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.SwitchBetweenLambdaAndLocalFunction, newLambda); hasSignatureErrors = true; return; } var oldLambdaSymbol = GetLambdaExpressionSymbol(oldModel, oldLambda, cancellationToken); var newLambdaSymbol = GetLambdaExpressionSymbol(newModel, newLambda, cancellationToken); // signature validation: if (!ParametersEquivalent(oldLambdaSymbol.Parameters, newLambdaSymbol.Parameters, exact: false)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingLambdaParameters, newLambda); hasSignatureErrors = true; } else if (!ReturnTypesEquivalent(oldLambdaSymbol, newLambdaSymbol, exact: false)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingLambdaReturnType, newLambda); hasSignatureErrors = true; } else if (!TypeParametersEquivalent(oldLambdaSymbol.TypeParameters, newLambdaSymbol.TypeParameters, exact: false)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingTypeParameters, newLambda); hasSignatureErrors = true; } if (hasSignatureErrors) { return; } // custom attributes ReportCustomAttributeRudeEdits(diagnostics, oldLambdaSymbol, newLambdaSymbol, newLambda, newModel.Compilation, capabilities, out _, out _, cancellationToken); for (var i = 0; i < oldLambdaSymbol.Parameters.Length; i++) { ReportCustomAttributeRudeEdits(diagnostics, oldLambdaSymbol.Parameters[i], newLambdaSymbol.Parameters[i], newLambda, newModel.Compilation, capabilities, out _, out _, cancellationToken); } for (var i = 0; i < oldLambdaSymbol.TypeParameters.Length; i++) { ReportCustomAttributeRudeEdits(diagnostics, oldLambdaSymbol.TypeParameters[i], newLambdaSymbol.TypeParameters[i], newLambda, newModel.Compilation, capabilities, out _, out _, cancellationToken); } } private static ITypeSymbol GetType(ISymbol localOrParameter) => localOrParameter.Kind switch { SymbolKind.Parameter => ((IParameterSymbol)localOrParameter).Type, SymbolKind.Local => ((ILocalSymbol)localOrParameter).Type, _ => throw ExceptionUtilities.UnexpectedValue(localOrParameter.Kind), }; private SyntaxNode GetCapturedVariableScope(ISymbol localOrParameter, SyntaxNode memberBody, CancellationToken cancellationToken) { Debug.Assert(localOrParameter.Kind != SymbolKind.RangeVariable); if (localOrParameter.Kind == SymbolKind.Parameter) { var member = localOrParameter.ContainingSymbol; // lambda parameters and C# constructor parameters are lifted to their own scope: if ((member as IMethodSymbol)?.MethodKind == MethodKind.AnonymousFunction || HasParameterClosureScope(member)) { var result = localOrParameter.DeclaringSyntaxReferences.Single().GetSyntax(cancellationToken); Debug.Assert(IsLambda(result)); return result; } return memberBody; } var node = localOrParameter.DeclaringSyntaxReferences.Single().GetSyntax(cancellationToken); while (true) { RoslynDebug.Assert(node is object); if (IsClosureScope(node)) { return node; } node = node.Parent; } } private static bool AreEquivalentClosureScopes(SyntaxNode oldScopeOpt, SyntaxNode newScopeOpt, IReadOnlyDictionary<SyntaxNode, SyntaxNode> reverseMap) { if (oldScopeOpt == null || newScopeOpt == null) { return oldScopeOpt == newScopeOpt; } return reverseMap.TryGetValue(newScopeOpt, out var mappedScope) && mappedScope == oldScopeOpt; } #endregion #region State Machines private void ReportStateMachineRudeEdits( Compilation oldCompilation, ISymbol oldMember, SyntaxNode newBody, ArrayBuilder<RudeEditDiagnostic> diagnostics) { // Only methods, local functions and anonymous functions can be async/iterators machines, // but don't assume so to be resiliant against errors in code. if (oldMember is not IMethodSymbol oldMethod) { return; } var stateMachineAttributeQualifiedName = oldMethod.IsAsync ? "System.Runtime.CompilerServices.AsyncStateMachineAttribute" : "System.Runtime.CompilerServices.IteratorStateMachineAttribute"; // We assume that the attributes, if exist, are well formed. // If not an error will be reported during EnC delta emit. // Report rude edit if the type is not found in the compilation. // Consider: This diagnostic is cached in the document analysis, // so it could happen that the attribute type is added later to // the compilation and we continue to report the diagnostic. // We could report rude edit when adding these types or flush all // (or specific) document caches. This is not a common scenario though, // since the attribute has been long defined in the BCL. if (oldCompilation.GetTypeByMetadataName(stateMachineAttributeQualifiedName) == null) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.UpdatingStateMachineMethodMissingAttribute, GetBodyDiagnosticSpan(newBody, EditKind.Update), newBody, new[] { stateMachineAttributeQualifiedName })); } } #endregion #endregion #region Helpers private static SyntaxNode? TryGetNode(SyntaxNode root, int position) => root.FullSpan.Contains(position) ? root.FindToken(position).Parent : null; internal static void AddNodes<T>(ArrayBuilder<SyntaxNode> nodes, SyntaxList<T> list) where T : SyntaxNode { foreach (var node in list) { nodes.Add(node); } } internal static void AddNodes<T>(ArrayBuilder<SyntaxNode> nodes, SeparatedSyntaxList<T>? list) where T : SyntaxNode { if (list.HasValue) { foreach (var node in list.Value) { nodes.Add(node); } } } private sealed class TypedConstantComparer : IEqualityComparer<TypedConstant> { public static TypedConstantComparer Instance = new TypedConstantComparer(); public bool Equals(TypedConstant x, TypedConstant y) => x.Kind.Equals(y.Kind) && x.IsNull.Equals(y.IsNull) && SymbolEquivalenceComparer.Instance.Equals(x.Type, y.Type) && x.Kind switch { TypedConstantKind.Array => x.Values.SequenceEqual(y.Values, TypedConstantComparer.Instance), _ => object.Equals(x.Value, y.Value) }; public int GetHashCode(TypedConstant obj) => obj.GetHashCode(); } private sealed class NamedArgumentComparer : IEqualityComparer<KeyValuePair<string, TypedConstant>> { public static NamedArgumentComparer Instance = new NamedArgumentComparer(); public bool Equals(KeyValuePair<string, TypedConstant> x, KeyValuePair<string, TypedConstant> y) => x.Key.Equals(y.Key) && TypedConstantComparer.Instance.Equals(x.Value, y.Value); public int GetHashCode(KeyValuePair<string, TypedConstant> obj) => obj.GetHashCode(); } #pragma warning disable format private static bool IsGlobalMain(ISymbol symbol) => symbol is IMethodSymbol { Name: WellKnownMemberNames.TopLevelStatementsEntryPointMethodName, ContainingType.Name: WellKnownMemberNames.TopLevelStatementsEntryPointTypeName }; #pragma warning restore format private static bool InGenericContext(ISymbol symbol, out bool isGenericMethod) { var current = symbol; while (true) { if (current is IMethodSymbol { Arity: > 0 }) { isGenericMethod = true; return true; } if (current is INamedTypeSymbol { Arity: > 0 }) { isGenericMethod = false; return true; } current = current.ContainingSymbol; if (current == null) { isGenericMethod = false; return false; } } } #endregion #region Testing internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly AbstractEditAndContinueAnalyzer _abstractEditAndContinueAnalyzer; public TestAccessor(AbstractEditAndContinueAnalyzer abstractEditAndContinueAnalyzer) => _abstractEditAndContinueAnalyzer = abstractEditAndContinueAnalyzer; internal void ReportTopLevelSyntacticRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, EditScript<SyntaxNode> syntacticEdits, Dictionary<SyntaxNode, EditKind> editMap) => _abstractEditAndContinueAnalyzer.ReportTopLevelSyntacticRudeEdits(diagnostics, syntacticEdits, editMap); internal BidirectionalMap<SyntaxNode> ComputeMap( Match<SyntaxNode> bodyMatch, ArrayBuilder<ActiveNode> activeNodes, ref Dictionary<SyntaxNode, LambdaInfo>? lazyActiveOrMatchedLambdas, ArrayBuilder<RudeEditDiagnostic> diagnostics) { return _abstractEditAndContinueAnalyzer.ComputeMap(bodyMatch, activeNodes, ref lazyActiveOrMatchedLambdas, diagnostics); } internal Match<SyntaxNode> ComputeBodyMatch( SyntaxNode oldBody, SyntaxNode newBody, ActiveNode[] activeNodes, ArrayBuilder<RudeEditDiagnostic> diagnostics, out bool oldHasStateMachineSuspensionPoint, out bool newHasStateMachineSuspensionPoint) { return _abstractEditAndContinueAnalyzer.ComputeBodyMatch(oldBody, newBody, activeNodes, diagnostics, out oldHasStateMachineSuspensionPoint, out newHasStateMachineSuspensionPoint); } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Differencing; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { internal abstract class AbstractEditAndContinueAnalyzer : IEditAndContinueAnalyzer { internal const int DefaultStatementPart = 0; private const string CreateNewOnMetadataUpdateAttributeName = "CreateNewOnMetadataUpdateAttribute"; /// <summary> /// Contains enough information to determine whether two symbols have the same signature. /// </summary> private static readonly SymbolDisplayFormat s_unqualifiedMemberDisplayFormat = new( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameOnly, propertyStyle: SymbolDisplayPropertyStyle.NameOnly, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeExplicitInterface, parameterOptions: SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeExtensionThis | SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes); private static readonly SymbolDisplayFormat s_fullyQualifiedMemberDisplayFormat = new( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, propertyStyle: SymbolDisplayPropertyStyle.NameOnly, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeContainingType, parameterOptions: SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeExtensionThis | SymbolDisplayParameterOptions.IncludeType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes); // used by tests to validate correct handlign of unexpected exceptions private readonly Action<SyntaxNode>? _testFaultInjector; protected AbstractEditAndContinueAnalyzer(Action<SyntaxNode>? testFaultInjector) { _testFaultInjector = testFaultInjector; } internal abstract bool ExperimentalFeaturesEnabled(SyntaxTree tree); /// <summary> /// Finds member declaration node(s) containing given <paramref name="node"/>. /// Specified <paramref name="node"/> may be either a node of the declaration body or an active node that belongs to the declaration. /// </summary> /// <remarks> /// The implementation has to decide what kinds of nodes in top-level match relationship represent a declaration. /// Every member declaration must be represented by exactly one node, but not all nodes have to represent a declaration. /// /// Note that in some cases the set of nodes of the declaration body may differ from the set of active nodes that /// belong to the declaration. For example, in <c>Dim a, b As New T</c> the sets for member <c>a</c> are /// { <c>New</c>, <c>T</c> } and { <c>a</c> }, respectively. /// /// May return multiple declarations if the specified <paramref name="node"/> belongs to multiple declarations, /// such as in VB <c>Dim a, b As New T</c> case when <paramref name="node"/> is e.g. <c>T</c>. /// </remarks> internal abstract bool TryFindMemberDeclaration(SyntaxNode? root, SyntaxNode node, out OneOrMany<SyntaxNode> declarations); /// <summary> /// If the specified node represents a member declaration returns a node that represents its body, /// i.e. a node used as the root of statement-level match. /// </summary> /// <param name="node">A node representing a declaration or a top-level edit node.</param> /// /// <returns> /// Returns null for nodes that don't represent declarations. /// </returns> /// <remarks> /// The implementation has to decide what kinds of nodes in top-level match relationship represent a declaration. /// Every member declaration must be represented by exactly one node, but not all nodes have to represent a declaration. /// /// If a member doesn't have a body (null is returned) it can't have associated active statements. /// /// Body does not need to cover all active statements that may be associated with the member. /// E.g. Body of a C# constructor is the method body block. Active statements may be placed on the base constructor call. /// Body of a VB field declaration with shared AsNew initializer is the New expression. Active statements might be placed on the field variables. /// <see cref="FindStatementAndPartner"/> has to account for such cases. /// </remarks> internal abstract SyntaxNode? TryGetDeclarationBody(SyntaxNode node); /// <summary> /// True if the specified <paramref name="declaration"/> node shares body with another declaration. /// </summary> internal abstract bool IsDeclarationWithSharedBody(SyntaxNode declaration); /// <summary> /// If the specified node represents a member declaration returns all tokens of the member declaration /// that might be covered by an active statement. /// </summary> /// <returns> /// Tokens covering all possible breakpoint spans associated with the member, /// or null if the specified node doesn't represent a member declaration or /// doesn't have a body that can contain active statements. /// </returns> /// <remarks> /// The implementation has to decide what kinds of nodes in top-level match relationship represent a declaration. /// Every member declaration must be represented by exactly one node, but not all nodes have to represent a declaration. /// /// TODO: consider implementing this via <see cref="GetActiveSpanEnvelope"/>. /// </remarks> internal abstract IEnumerable<SyntaxToken>? TryGetActiveTokens(SyntaxNode node); /// <summary> /// Returns a span that contains all possible breakpoint spans of the <paramref name="declaration"/> /// and no breakpoint spans that do not belong to the <paramref name="declaration"/>. /// /// Returns default if the declaration does not have any breakpoint spans. /// </summary> internal abstract (TextSpan envelope, TextSpan hole) GetActiveSpanEnvelope(SyntaxNode declaration); /// <summary> /// Returns an ancestor that encompasses all active and statement level /// nodes that belong to the member represented by <paramref name="bodyOrMatchRoot"/>. /// </summary> protected SyntaxNode? GetEncompassingAncestor(SyntaxNode? bodyOrMatchRoot) { if (bodyOrMatchRoot == null) { return null; } var root = GetEncompassingAncestorImpl(bodyOrMatchRoot); Debug.Assert(root.Span.Contains(bodyOrMatchRoot.Span)); return root; } protected abstract SyntaxNode GetEncompassingAncestorImpl(SyntaxNode bodyOrMatchRoot); /// <summary> /// Finds a statement at given span and a declaration body. /// Also returns the corresponding partner statement in <paramref name="partnerDeclarationBody"/>, if specified. /// </summary> /// <remarks> /// The declaration body node may not contain the <paramref name="span"/>. /// This happens when an active statement associated with the member is outside of its body /// (e.g. C# constructor, or VB <c>Dim a,b As New T</c>). /// If the position doesn't correspond to any statement uses the start of the <paramref name="declarationBody"/>. /// </remarks> protected abstract SyntaxNode FindStatementAndPartner(SyntaxNode declarationBody, TextSpan span, SyntaxNode? partnerDeclarationBody, out SyntaxNode? partner, out int statementPart); private SyntaxNode FindStatement(SyntaxNode declarationBody, TextSpan span, out int statementPart) => FindStatementAndPartner(declarationBody, span, null, out _, out statementPart); /// <summary> /// Maps <paramref name="leftNode"/> of a body of <paramref name="leftDeclaration"/> to corresponding body node /// of <paramref name="rightDeclaration"/>, assuming that the declaration bodies only differ in trivia. /// </summary> internal abstract SyntaxNode FindDeclarationBodyPartner(SyntaxNode leftDeclaration, SyntaxNode rightDeclaration, SyntaxNode leftNode); /// <summary> /// Returns a node that represents a body of a lambda containing specified <paramref name="node"/>, /// or null if the node isn't contained in a lambda. If a node is returned it must uniquely represent the lambda, /// i.e. be no two distinct nodes may represent the same lambda. /// </summary> protected abstract SyntaxNode? FindEnclosingLambdaBody(SyntaxNode? container, SyntaxNode node); /// <summary> /// Given a node that represents a lambda body returns all nodes of the body in a syntax list. /// </summary> /// <remarks> /// Note that VB lambda bodies are represented by a lambda header and that some lambda bodies share /// their parent nodes with other bodies (e.g. join clause expressions). /// </remarks> protected abstract IEnumerable<SyntaxNode> GetLambdaBodyExpressionsAndStatements(SyntaxNode lambdaBody); protected abstract SyntaxNode? TryGetPartnerLambdaBody(SyntaxNode oldBody, SyntaxNode newLambda); protected abstract Match<SyntaxNode> ComputeTopLevelMatch(SyntaxNode oldCompilationUnit, SyntaxNode newCompilationUnit); protected abstract Match<SyntaxNode> ComputeBodyMatch(SyntaxNode oldBody, SyntaxNode newBody, IEnumerable<KeyValuePair<SyntaxNode, SyntaxNode>>? knownMatches); protected abstract Match<SyntaxNode> ComputeTopLevelDeclarationMatch(SyntaxNode oldDeclaration, SyntaxNode newDeclaration); protected abstract IEnumerable<SequenceEdit> GetSyntaxSequenceEdits(ImmutableArray<SyntaxNode> oldNodes, ImmutableArray<SyntaxNode> newNodes); /// <summary> /// Matches old active statement to new active statement without constructing full method body match. /// This is needed for active statements that are outside of method body, like constructor initializer. /// </summary> protected abstract bool TryMatchActiveStatement( SyntaxNode oldStatement, int statementPart, SyntaxNode oldBody, SyntaxNode newBody, [NotNullWhen(true)] out SyntaxNode? newStatement); protected abstract bool TryGetEnclosingBreakpointSpan(SyntaxNode root, int position, out TextSpan span); /// <summary> /// Get the active span that corresponds to specified node (or its part). /// </summary> /// <returns> /// True if the node has an active span associated with it, false otherwise. /// </returns> protected abstract bool TryGetActiveSpan(SyntaxNode node, int statementPart, int minLength, out TextSpan span); /// <summary> /// Yields potential active statements around the specified active statement /// starting with siblings following the statement, then preceding the statement, follows with its parent, its following siblings, etc. /// </summary> /// <returns> /// Pairs of (node, statement part), or (node, -1) indicating there is no logical following statement. /// The enumeration continues until the root is reached. /// </returns> protected abstract IEnumerable<(SyntaxNode statement, int statementPart)> EnumerateNearStatements(SyntaxNode statement); protected abstract bool StatementLabelEquals(SyntaxNode node1, SyntaxNode node2); /// <summary> /// True if both nodes represent the same kind of suspension point /// (await expression, await foreach statement, await using declarator, yield return, yield break). /// </summary> protected virtual bool StateMachineSuspensionPointKindEquals(SyntaxNode suspensionPoint1, SyntaxNode suspensionPoint2) => suspensionPoint1.RawKind == suspensionPoint2.RawKind; /// <summary> /// Determines if two syntax nodes are the same, disregarding trivia differences. /// </summary> protected abstract bool AreEquivalent(SyntaxNode left, SyntaxNode right); /// <summary> /// Returns true if the code emitted for the old active statement part (<paramref name="statementPart"/> of <paramref name="oldStatement"/>) /// is the same as the code emitted for the corresponding new active statement part (<paramref name="statementPart"/> of <paramref name="newStatement"/>). /// </summary> /// <remarks> /// A rude edit is reported if an active statement is changed and this method returns true. /// </remarks> protected abstract bool AreEquivalentActiveStatements(SyntaxNode oldStatement, SyntaxNode newStatement, int statementPart); protected abstract TextSpan GetGlobalStatementDiagnosticSpan(SyntaxNode node); /// <summary> /// Returns all symbols associated with an edit and an actual edit kind, which may be different then the specified one. /// Returns an empty set if the edit is not associated with any symbols. /// </summary> protected abstract OneOrMany<(ISymbol? oldSymbol, ISymbol? newSymbol, EditKind editKind)> GetSymbolEdits( EditKind editKind, SyntaxNode? oldNode, SyntaxNode? newNode, SemanticModel? oldModel, SemanticModel newModel, IReadOnlyDictionary<SyntaxNode, EditKind> editMap, CancellationToken cancellationToken); /// <summary> /// Analyzes data flow in the member body represented by the specified node and returns all captured variables and parameters (including "this"). /// If the body is a field/property initializer analyzes the initializer expression only. /// </summary> protected abstract ImmutableArray<ISymbol> GetCapturedVariables(SemanticModel model, SyntaxNode memberBody); /// <summary> /// Enumerates all use sites of a specified variable within the specified syntax subtrees. /// </summary> protected abstract IEnumerable<SyntaxNode> GetVariableUseSites(IEnumerable<SyntaxNode> roots, ISymbol localOrParameter, SemanticModel model, CancellationToken cancellationToken); protected abstract bool AreHandledEventsEqual(IMethodSymbol oldMethod, IMethodSymbol newMethod); // diagnostic spans: protected abstract TextSpan? TryGetDiagnosticSpan(SyntaxNode node, EditKind editKind); internal TextSpan GetDiagnosticSpan(SyntaxNode node, EditKind editKind) => TryGetDiagnosticSpan(node, editKind) ?? node.Span; protected virtual TextSpan GetBodyDiagnosticSpan(SyntaxNode node, EditKind editKind) { var current = node.Parent; while (true) { if (current == null) { return node.Span; } var span = TryGetDiagnosticSpan(current, editKind); if (span != null) { return span.Value; } current = current.Parent; } } internal abstract TextSpan GetLambdaParameterDiagnosticSpan(SyntaxNode lambda, int ordinal); // display names: internal string GetDisplayName(SyntaxNode node, EditKind editKind = EditKind.Update) => TryGetDisplayName(node, editKind) ?? throw ExceptionUtilities.UnexpectedValue(node.GetType().Name); internal string GetDisplayName(ISymbol symbol) => symbol.Kind switch { SymbolKind.Event => FeaturesResources.event_, SymbolKind.Field => GetDisplayName((IFieldSymbol)symbol), SymbolKind.Method => GetDisplayName((IMethodSymbol)symbol), SymbolKind.NamedType => GetDisplayName((INamedTypeSymbol)symbol), SymbolKind.Parameter => FeaturesResources.parameter, SymbolKind.Property => GetDisplayName((IPropertySymbol)symbol), SymbolKind.TypeParameter => FeaturesResources.type_parameter, _ => throw ExceptionUtilities.UnexpectedValue(symbol.Kind) }; internal virtual string GetDisplayName(IPropertySymbol symbol) => FeaturesResources.property_; internal virtual string GetDisplayName(INamedTypeSymbol symbol) => symbol.TypeKind switch { TypeKind.Class => FeaturesResources.class_, TypeKind.Interface => FeaturesResources.interface_, TypeKind.Delegate => FeaturesResources.delegate_, TypeKind.Enum => FeaturesResources.enum_, TypeKind.TypeParameter => FeaturesResources.type_parameter, _ => FeaturesResources.type, }; internal virtual string GetDisplayName(IFieldSymbol symbol) => symbol.IsConst ? ((symbol.ContainingType.TypeKind == TypeKind.Enum) ? FeaturesResources.enum_value : FeaturesResources.const_field) : FeaturesResources.field; internal virtual string GetDisplayName(IMethodSymbol symbol) => symbol.MethodKind switch { MethodKind.Constructor => FeaturesResources.constructor, MethodKind.PropertyGet or MethodKind.PropertySet => FeaturesResources.property_accessor, MethodKind.EventAdd or MethodKind.EventRaise or MethodKind.EventRemove => FeaturesResources.event_accessor, MethodKind.BuiltinOperator or MethodKind.UserDefinedOperator or MethodKind.Conversion => FeaturesResources.operator_, _ => FeaturesResources.method, }; /// <summary> /// Returns the display name of an ancestor node that contains the specified node and has a display name. /// </summary> protected virtual string GetBodyDisplayName(SyntaxNode node, EditKind editKind = EditKind.Update) { var current = node.Parent; while (true) { if (current == null) { throw ExceptionUtilities.UnexpectedValue(node.GetType().Name); } var displayName = TryGetDisplayName(current, editKind); if (displayName != null) { return displayName; } current = current.Parent; } } protected abstract string? TryGetDisplayName(SyntaxNode node, EditKind editKind); protected virtual string GetSuspensionPointDisplayName(SyntaxNode node, EditKind editKind) => GetDisplayName(node, editKind); protected abstract string LineDirectiveKeyword { get; } protected abstract ushort LineDirectiveSyntaxKind { get; } protected abstract SymbolDisplayFormat ErrorDisplayFormat { get; } protected abstract List<SyntaxNode> GetExceptionHandlingAncestors(SyntaxNode node, bool isNonLeaf); protected abstract void GetStateMachineInfo(SyntaxNode body, out ImmutableArray<SyntaxNode> suspensionPoints, out StateMachineKinds kinds); protected abstract TextSpan GetExceptionHandlingRegion(SyntaxNode node, out bool coversAllChildren); protected abstract void ReportLocalFunctionsDeclarationRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> bodyMatch); internal abstract void ReportTopLevelSyntacticRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, Edit<SyntaxNode> edit, Dictionary<SyntaxNode, EditKind> editMap); internal abstract void ReportEnclosingExceptionHandlingRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, IEnumerable<Edit<SyntaxNode>> exceptionHandlingEdits, SyntaxNode oldStatement, TextSpan newStatementSpan); internal abstract void ReportOtherRudeEditsAroundActiveStatement(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode oldStatement, SyntaxNode newStatement, bool isNonLeaf); internal abstract void ReportMemberBodyUpdateRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode newMember, TextSpan? span); internal abstract void ReportInsertedMemberSymbolRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol newSymbol, SyntaxNode newNode, bool insertingIntoExistingContainingType); internal abstract void ReportStateMachineSuspensionPointRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldNode, SyntaxNode newNode); internal abstract bool IsLambda(SyntaxNode node); internal abstract bool IsInterfaceDeclaration(SyntaxNode node); internal abstract bool IsRecordDeclaration(SyntaxNode node); /// <summary> /// True if the node represents any form of a function definition nested in another function body (i.e. anonymous function, lambda, local function). /// </summary> internal abstract bool IsNestedFunction(SyntaxNode node); internal abstract bool IsLocalFunction(SyntaxNode node); internal abstract bool IsClosureScope(SyntaxNode node); internal abstract bool ContainsLambda(SyntaxNode declaration); internal abstract SyntaxNode GetLambda(SyntaxNode lambdaBody); internal abstract IMethodSymbol GetLambdaExpressionSymbol(SemanticModel model, SyntaxNode lambdaExpression, CancellationToken cancellationToken); internal abstract SyntaxNode? GetContainingQueryExpression(SyntaxNode node); internal abstract bool QueryClauseLambdasTypeEquivalent(SemanticModel oldModel, SyntaxNode oldNode, SemanticModel newModel, SyntaxNode newNode, CancellationToken cancellationToken); /// <summary> /// Returns true if the parameters of the symbol are lifted into a scope that is different from the symbol's body. /// </summary> internal abstract bool HasParameterClosureScope(ISymbol member); /// <summary> /// Returns all lambda bodies of a node representing a lambda, /// or false if the node doesn't represent a lambda. /// </summary> /// <remarks> /// C# anonymous function expression and VB lambda expression both have a single body /// (in VB the body is the header of the lambda expression). /// /// Some lambda queries (group by, join by) have two bodies. /// </remarks> internal abstract bool TryGetLambdaBodies(SyntaxNode node, [NotNullWhen(true)] out SyntaxNode? body1, out SyntaxNode? body2); internal abstract bool IsStateMachineMethod(SyntaxNode declaration); /// <summary> /// Returns the type declaration that contains a specified <paramref name="node"/>. /// This can be class, struct, interface, record or enum declaration. /// </summary> internal abstract SyntaxNode? TryGetContainingTypeDeclaration(SyntaxNode node); /// <summary> /// Returns the declaration of /// - a property, indexer or event declaration whose accessor is the specified <paramref name="node"/>, /// - a method, an indexer or a type (delegate) if the <paramref name="node"/> is a parameter, /// - a method or an type if the <paramref name="node"/> is a type parameter. /// </summary> internal abstract bool TryGetAssociatedMemberDeclaration(SyntaxNode node, [NotNullWhen(true)] out SyntaxNode? declaration); internal abstract bool HasBackingField(SyntaxNode propertyDeclaration); /// <summary> /// Return true if the declaration is a field/property declaration with an initializer. /// Shall return false for enum members. /// </summary> internal abstract bool IsDeclarationWithInitializer(SyntaxNode declaration); /// <summary> /// Return true if the declaration is a parameter that is part of a records primary constructor. /// </summary> internal abstract bool IsRecordPrimaryConstructorParameter(SyntaxNode declaration); /// <summary> /// Return true if the declaration is a property accessor for a property that represents one of the parameters in a records primary constructor. /// </summary> internal abstract bool IsPropertyAccessorDeclarationMatchingPrimaryConstructorParameter(SyntaxNode declaration, INamedTypeSymbol newContainingType, out bool isFirstAccessor); /// <summary> /// Return true if the declaration is a constructor declaration to which field/property initializers are emitted. /// </summary> internal abstract bool IsConstructorWithMemberInitializers(SyntaxNode declaration); internal abstract bool IsPartial(INamedTypeSymbol type); internal abstract SyntaxNode EmptyCompilationUnit { get; } private static readonly SourceText s_emptySource = SourceText.From(""); #region Document Analysis public async Task<DocumentAnalysisResults> AnalyzeDocumentAsync( Project oldProject, ActiveStatementsMap oldActiveStatementMap, Document newDocument, ImmutableArray<LinePositionSpan> newActiveStatementSpans, EditAndContinueCapabilities capabilities, CancellationToken cancellationToken) { DocumentAnalysisResults.Log.Write("Analyzing document {0}", newDocument.Name); Debug.Assert(!newActiveStatementSpans.IsDefault); Debug.Assert(newDocument.SupportsSyntaxTree); Debug.Assert(newDocument.SupportsSemanticModel); // assume changes until we determine there are none so that EnC is blocked on unexpected exception: var hasChanges = true; try { cancellationToken.ThrowIfCancellationRequested(); SyntaxTree? oldTree; SyntaxNode oldRoot; SourceText oldText; var oldDocument = await oldProject.GetDocumentAsync(newDocument.Id, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); if (oldDocument != null) { oldTree = await oldDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(oldTree); oldRoot = await oldTree.GetRootAsync(cancellationToken).ConfigureAwait(false); oldText = await oldDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); } else { oldTree = null; oldRoot = EmptyCompilationUnit; oldText = s_emptySource; } var newTree = await newDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(newTree); // Changes in parse options might change the meaning of the code even if nothing else changed. // The IDE should disallow changing the options during debugging session. Debug.Assert(oldTree == null || oldTree.Options.Equals(newTree.Options)); var newRoot = await newTree.GetRootAsync(cancellationToken).ConfigureAwait(false); var newText = await newDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); hasChanges = !oldText.ContentEquals(newText); _testFaultInjector?.Invoke(newRoot); cancellationToken.ThrowIfCancellationRequested(); // TODO: newTree.HasErrors? var syntaxDiagnostics = newRoot.GetDiagnostics(); var hasSyntaxError = syntaxDiagnostics.Any(d => d.Severity == DiagnosticSeverity.Error); if (hasSyntaxError) { // Bail, since we can't do syntax diffing on broken trees (it would not produce useful results anyways). // If we needed to do so for some reason, we'd need to harden the syntax tree comparers. DocumentAnalysisResults.Log.Write("{0}: syntax errors", newDocument.Name); return DocumentAnalysisResults.SyntaxErrors(newDocument.Id, ImmutableArray<RudeEditDiagnostic>.Empty, hasChanges); } if (!hasChanges) { // The document might have been closed and reopened, which might have triggered analysis. // If the document is unchanged don't continue the analysis since // a) comparing texts is cheaper than diffing trees // b) we need to ignore errors in unchanged documents DocumentAnalysisResults.Log.Write("{0}: unchanged", newDocument.Name); return DocumentAnalysisResults.Unchanged(newDocument.Id); } // If the document has changed at all, lets make sure Edit and Continue is supported if (!capabilities.HasFlag(EditAndContinueCapabilities.Baseline)) { return DocumentAnalysisResults.SyntaxErrors(newDocument.Id, ImmutableArray.Create( new RudeEditDiagnostic(RudeEditKind.NotSupportedByRuntime, default)), hasChanges); } // Disallow modification of a file with experimental features enabled. // These features may not be handled well by the analysis below. if (ExperimentalFeaturesEnabled(newTree)) { DocumentAnalysisResults.Log.Write("{0}: experimental features enabled", newDocument.Name); return DocumentAnalysisResults.SyntaxErrors(newDocument.Id, ImmutableArray.Create( new RudeEditDiagnostic(RudeEditKind.ExperimentalFeaturesEnabled, default)), hasChanges); } // We are in break state when there are no active statements. var inBreakState = !oldActiveStatementMap.IsEmpty; // We do calculate diffs even if there are semantic errors for the following reasons: // 1) We need to be able to find active spans in the new document. // If we didn't calculate them we would only rely on tracking spans (might be ok). // 2) If there are syntactic rude edits we'll report them faster without waiting for semantic analysis. // The user may fix them before they address all the semantic errors. using var _2 = ArrayBuilder<RudeEditDiagnostic>.GetInstance(out var diagnostics); cancellationToken.ThrowIfCancellationRequested(); var topMatch = ComputeTopLevelMatch(oldRoot, newRoot); var syntacticEdits = topMatch.GetTreeEdits(); var editMap = BuildEditMap(syntacticEdits); var hasRudeEdits = false; ReportTopLevelSyntacticRudeEdits(diagnostics, syntacticEdits, editMap); if (diagnostics.Count > 0 && !hasRudeEdits) { DocumentAnalysisResults.Log.Write("{0} syntactic rude edits, first: '{1}'", diagnostics.Count, newDocument.FilePath); hasRudeEdits = true; } cancellationToken.ThrowIfCancellationRequested(); using var _3 = ArrayBuilder<(SyntaxNode OldNode, SyntaxNode NewNode, TextSpan DiagnosticSpan)>.GetInstance(out var triviaEdits); using var _4 = ArrayBuilder<SequencePointUpdates>.GetInstance(out var lineEdits); AnalyzeTrivia( topMatch, editMap, triviaEdits, lineEdits, cancellationToken); cancellationToken.ThrowIfCancellationRequested(); var oldActiveStatements = (oldTree == null) ? ImmutableArray<UnmappedActiveStatement>.Empty : oldActiveStatementMap.GetOldActiveStatements(this, oldTree, oldText, oldRoot, cancellationToken); var newActiveStatements = ImmutableArray.CreateBuilder<ActiveStatement>(oldActiveStatements.Length); newActiveStatements.Count = oldActiveStatements.Length; var newExceptionRegions = ImmutableArray.CreateBuilder<ImmutableArray<SourceFileSpan>>(oldActiveStatements.Length); newExceptionRegions.Count = oldActiveStatements.Length; var semanticEdits = await AnalyzeSemanticsAsync( syntacticEdits, editMap, oldActiveStatements, newActiveStatementSpans, triviaEdits, oldProject, oldDocument, newDocument, newText, diagnostics, newActiveStatements, newExceptionRegions, capabilities, inBreakState, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); AnalyzeUnchangedActiveMemberBodies(diagnostics, syntacticEdits.Match, newText, oldActiveStatements, newActiveStatementSpans, newActiveStatements, newExceptionRegions, cancellationToken); Debug.Assert(newActiveStatements.All(a => a != null)); if (diagnostics.Count > 0 && !hasRudeEdits) { DocumentAnalysisResults.Log.Write("{0}@{1}: rude edit ({2} total)", newDocument.FilePath, diagnostics.First().Span.Start, diagnostics.Count); hasRudeEdits = true; } return new DocumentAnalysisResults( newDocument.Id, newActiveStatements.MoveToImmutable(), diagnostics.ToImmutable(), hasRudeEdits ? default : semanticEdits, hasRudeEdits ? default : newExceptionRegions.MoveToImmutable(), hasRudeEdits ? default : lineEdits.ToImmutable(), hasChanges: true, hasSyntaxErrors: false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { // The same behavior as if there was a syntax error - we are unable to analyze the document. // We expect OOM to be thrown during the analysis if the number of top-level entities is too large. // In such case we report a rude edit for the document. If the host is actually running out of memory, // it might throw another OOM here or later on. var diagnostic = (e is OutOfMemoryException) ? new RudeEditDiagnostic(RudeEditKind.SourceFileTooBig, span: default, arguments: new[] { newDocument.FilePath }) : new RudeEditDiagnostic(RudeEditKind.InternalError, span: default, arguments: new[] { newDocument.FilePath, e.ToString() }); // Report as "syntax error" - we can't analyze the document return DocumentAnalysisResults.SyntaxErrors(newDocument.Id, ImmutableArray.Create(diagnostic), hasChanges); } } private void ReportTopLevelSyntacticRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, EditScript<SyntaxNode> syntacticEdits, Dictionary<SyntaxNode, EditKind> editMap) { foreach (var edit in syntacticEdits.Edits) { ReportTopLevelSyntacticRudeEdits(diagnostics, syntacticEdits.Match, edit, editMap); } } /// <summary> /// Reports rude edits for a symbol that's been deleted in one location and inserted in another and the edit was not classified as /// <see cref="EditKind.Move"/> or <see cref="EditKind.Reorder"/>. /// The scenarios include moving a type declaration from one file to another and moving a member of a partial type from one partial declaration to another. /// </summary> internal virtual void ReportDeclarationInsertDeleteRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldNode, SyntaxNode newNode, ISymbol oldSymbol, ISymbol newSymbol, CancellationToken cancellationToken) { // When a method is moved to a different declaration and its parameters are changed at the same time // the new method symbol key will not resolve to the old one since the parameters are different. // As a result we will report separate delete and insert rude edits. // // For delegates, however, the symbol key will resolve to the old type so we need to report // rude edits here. if (oldSymbol is INamedTypeSymbol { DelegateInvokeMethod: not null and var oldDelegateInvoke } && newSymbol is INamedTypeSymbol { DelegateInvokeMethod: not null and var newDelegateInvoke }) { if (!ParametersEquivalent(oldDelegateInvoke.Parameters, newDelegateInvoke.Parameters, exact: false)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingParameterTypes, newSymbol, newNode, cancellationToken); } } } internal static Dictionary<SyntaxNode, EditKind> BuildEditMap(EditScript<SyntaxNode> editScript) { var map = new Dictionary<SyntaxNode, EditKind>(editScript.Edits.Length); foreach (var edit in editScript.Edits) { // do not include reorder and move edits if (edit.Kind is EditKind.Delete or EditKind.Update) { map.Add(edit.OldNode, edit.Kind); } if (edit.Kind is EditKind.Insert or EditKind.Update) { map.Add(edit.NewNode, edit.Kind); } } return map; } #endregion #region Syntax Analysis private void AnalyzeUnchangedActiveMemberBodies( ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> topMatch, SourceText newText, ImmutableArray<UnmappedActiveStatement> oldActiveStatements, ImmutableArray<LinePositionSpan> newActiveStatementSpans, [In, Out] ImmutableArray<ActiveStatement>.Builder newActiveStatements, [In, Out] ImmutableArray<ImmutableArray<SourceFileSpan>>.Builder newExceptionRegions, CancellationToken cancellationToken) { Debug.Assert(!newActiveStatementSpans.IsDefault); Debug.Assert(newActiveStatementSpans.IsEmpty || oldActiveStatements.Length == newActiveStatementSpans.Length); Debug.Assert(oldActiveStatements.Length == newActiveStatements.Count); Debug.Assert(oldActiveStatements.Length == newExceptionRegions.Count); // Active statements in methods that were not updated // are not changed but their spans might have been. for (var i = 0; i < newActiveStatements.Count; i++) { if (newActiveStatements[i] == null) { Contract.ThrowIfFalse(newExceptionRegions[i].IsDefault); var oldStatementSpan = oldActiveStatements[i].UnmappedSpan; var node = TryGetNode(topMatch.OldRoot, oldStatementSpan.Start); // Guard against invalid active statement spans (in case PDB was somehow out of sync with the source). if (node != null && TryFindMemberDeclaration(topMatch.OldRoot, node, out var oldMemberDeclarations)) { foreach (var oldMember in oldMemberDeclarations) { var hasPartner = topMatch.TryGetNewNode(oldMember, out var newMember); Contract.ThrowIfFalse(hasPartner); var oldBody = TryGetDeclarationBody(oldMember); var newBody = TryGetDeclarationBody(newMember); // Guard against invalid active statement spans (in case PDB was somehow out of sync with the source). if (oldBody == null || newBody == null) { DocumentAnalysisResults.Log.Write("Invalid active statement span: [{0}..{1})", oldStatementSpan.Start, oldStatementSpan.End); continue; } var statementPart = -1; SyntaxNode? newStatement = null; // We seed the method body matching algorithm with tracking spans (unless they were deleted) // to get precise matching. if (TryGetTrackedStatement(newActiveStatementSpans, i, newText, newMember, newBody, out var trackedStatement, out var trackedStatementPart)) { // Adjust for active statements that cover more than the old member span. // For example, C# variable declarators that represent field initializers: // [|public int <<F = Expr()>>;|] var adjustedOldStatementStart = oldMember.FullSpan.Contains(oldStatementSpan.Start) ? oldStatementSpan.Start : oldMember.SpanStart; // The tracking span might have been moved outside of lambda. // It is not an error to move the statement - we just ignore it. var oldEnclosingLambdaBody = FindEnclosingLambdaBody(oldBody, oldMember.FindToken(adjustedOldStatementStart).Parent!); var newEnclosingLambdaBody = FindEnclosingLambdaBody(newBody, trackedStatement); if (oldEnclosingLambdaBody == newEnclosingLambdaBody) { newStatement = trackedStatement; statementPart = trackedStatementPart; } } if (newStatement == null) { Contract.ThrowIfFalse(statementPart == -1); FindStatementAndPartner(oldBody, oldStatementSpan, newBody, out newStatement, out statementPart); Contract.ThrowIfNull(newStatement); } if (diagnostics.Count == 0) { var ancestors = GetExceptionHandlingAncestors(newStatement, oldActiveStatements[i].Statement.IsNonLeaf); newExceptionRegions[i] = GetExceptionRegions(ancestors, newStatement.SyntaxTree, cancellationToken).Spans; } // Even though the body of the declaration haven't changed, // changes to its header might have caused the active span to become unavailable. // (e.g. In C# "const" was added to modifiers of a field with an initializer). var newStatementSpan = FindClosestActiveSpan(newStatement, statementPart); newActiveStatements[i] = GetActiveStatementWithSpan(oldActiveStatements[i], newBody.SyntaxTree, newStatementSpan, diagnostics, cancellationToken); } } else { DocumentAnalysisResults.Log.Write("Invalid active statement span: [{0}..{1})", oldStatementSpan.Start, oldStatementSpan.End); } // we were not able to determine the active statement location (PDB data might be invalid) if (newActiveStatements[i] == null) { newActiveStatements[i] = oldActiveStatements[i].Statement.WithSpan(default); newExceptionRegions[i] = ImmutableArray<SourceFileSpan>.Empty; } } } } internal readonly struct ActiveNode { public readonly int ActiveStatementIndex; public readonly SyntaxNode OldNode; public readonly SyntaxNode? NewTrackedNode; public readonly SyntaxNode? EnclosingLambdaBody; public readonly int StatementPart; public ActiveNode(int activeStatementIndex, SyntaxNode oldNode, SyntaxNode? enclosingLambdaBody, int statementPart, SyntaxNode? newTrackedNode) { ActiveStatementIndex = activeStatementIndex; OldNode = oldNode; NewTrackedNode = newTrackedNode; EnclosingLambdaBody = enclosingLambdaBody; StatementPart = statementPart; } } /// <summary> /// Information about an active and/or a matched lambda. /// </summary> internal readonly struct LambdaInfo { // non-null for an active lambda (lambda containing an active statement) public readonly List<int>? ActiveNodeIndices; // both fields are non-null for a matching lambda (lambda that exists in both old and new document): public readonly Match<SyntaxNode>? Match; public readonly SyntaxNode? NewBody; public LambdaInfo(List<int> activeNodeIndices) : this(activeNodeIndices, null, null) { } private LambdaInfo(List<int>? activeNodeIndices, Match<SyntaxNode>? match, SyntaxNode? newLambdaBody) { ActiveNodeIndices = activeNodeIndices; Match = match; NewBody = newLambdaBody; } public LambdaInfo WithMatch(Match<SyntaxNode> match, SyntaxNode newLambdaBody) => new(ActiveNodeIndices, match, newLambdaBody); } private void AnalyzeChangedMemberBody( SyntaxNode oldDeclaration, SyntaxNode newDeclaration, SyntaxNode oldBody, SyntaxNode? newBody, SemanticModel oldModel, SemanticModel newModel, ISymbol oldSymbol, ISymbol newSymbol, SourceText newText, ImmutableArray<UnmappedActiveStatement> oldActiveStatements, ImmutableArray<LinePositionSpan> newActiveStatementSpans, EditAndContinueCapabilities capabilities, [Out] ImmutableArray<ActiveStatement>.Builder newActiveStatements, [Out] ImmutableArray<ImmutableArray<SourceFileSpan>>.Builder newExceptionRegions, [Out] ArrayBuilder<RudeEditDiagnostic> diagnostics, out Func<SyntaxNode, SyntaxNode?>? syntaxMap, CancellationToken cancellationToken) { Debug.Assert(!newActiveStatementSpans.IsDefault); Debug.Assert(newActiveStatementSpans.IsEmpty || oldActiveStatements.Length == newActiveStatementSpans.Length); Debug.Assert(oldActiveStatements.IsEmpty || oldActiveStatements.Length == newActiveStatements.Count); Debug.Assert(newActiveStatements.Count == newExceptionRegions.Count); syntaxMap = null; var activeStatementIndices = GetOverlappingActiveStatements(oldDeclaration, oldActiveStatements); if (newBody == null) { // The body has been deleted. var newSpan = FindClosestActiveSpan(newDeclaration, DefaultStatementPart); Debug.Assert(newSpan != default); foreach (var activeStatementIndex in activeStatementIndices) { // We have already calculated the new location of this active statement when analyzing another member declaration. // This may only happen when two or more member declarations share the same body (VB AsNew clause). if (newActiveStatements[activeStatementIndex] != null) { Debug.Assert(IsDeclarationWithSharedBody(newDeclaration)); continue; } newActiveStatements[activeStatementIndex] = GetActiveStatementWithSpan(oldActiveStatements[activeStatementIndex], newDeclaration.SyntaxTree, newSpan, diagnostics, cancellationToken); newExceptionRegions[activeStatementIndex] = ImmutableArray<SourceFileSpan>.Empty; } return; } try { ReportMemberBodyUpdateRudeEdits(diagnostics, newDeclaration, GetDiagnosticSpan(newDeclaration, EditKind.Update)); _testFaultInjector?.Invoke(newBody); // Populated with active lambdas and matched lambdas. // Unmatched non-active lambdas are not included. // { old-lambda-body -> info } Dictionary<SyntaxNode, LambdaInfo>? lazyActiveOrMatchedLambdas = null; // finds leaf nodes that correspond to the old active statements: using var _ = ArrayBuilder<ActiveNode>.GetInstance(out var activeNodes); foreach (var activeStatementIndex in activeStatementIndices) { var oldStatementSpan = oldActiveStatements[activeStatementIndex].UnmappedSpan; var oldStatementSyntax = FindStatement(oldBody, oldStatementSpan, out var statementPart); Contract.ThrowIfNull(oldStatementSyntax); var oldEnclosingLambdaBody = FindEnclosingLambdaBody(oldBody, oldStatementSyntax); if (oldEnclosingLambdaBody != null) { lazyActiveOrMatchedLambdas ??= new Dictionary<SyntaxNode, LambdaInfo>(); if (!lazyActiveOrMatchedLambdas.TryGetValue(oldEnclosingLambdaBody, out var lambda)) { lambda = new LambdaInfo(new List<int>()); lazyActiveOrMatchedLambdas.Add(oldEnclosingLambdaBody, lambda); } lambda.ActiveNodeIndices!.Add(activeNodes.Count); } SyntaxNode? trackedNode = null; if (TryGetTrackedStatement(newActiveStatementSpans, activeStatementIndex, newText, newDeclaration, newBody, out var newStatementSyntax, out var _)) { var newEnclosingLambdaBody = FindEnclosingLambdaBody(newBody, newStatementSyntax); // The tracking span might have been moved outside of the lambda span. // It is not an error to move the statement - we just ignore it. if (oldEnclosingLambdaBody == newEnclosingLambdaBody && StatementLabelEquals(oldStatementSyntax, newStatementSyntax)) { trackedNode = newStatementSyntax; } } activeNodes.Add(new ActiveNode(activeStatementIndex, oldStatementSyntax, oldEnclosingLambdaBody, statementPart, trackedNode)); } var bodyMatch = ComputeBodyMatch(oldBody, newBody, activeNodes.Where(n => n.EnclosingLambdaBody == null).ToArray(), diagnostics, out var oldHasStateMachineSuspensionPoint, out var newHasStateMachineSuspensionPoint); var map = ComputeMap(bodyMatch, activeNodes, ref lazyActiveOrMatchedLambdas, diagnostics); if (oldHasStateMachineSuspensionPoint) { ReportStateMachineRudeEdits(oldModel.Compilation, oldSymbol, newBody, diagnostics); } else if (newHasStateMachineSuspensionPoint && !capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)) { // Adding a state machine, either for async or iterator, will require creating a new helper class // so is a rude edit if the runtime doesn't support it if (newSymbol is IMethodSymbol { IsAsync: true }) { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.MakeMethodAsync, GetDiagnosticSpan(newDeclaration, EditKind.Insert))); } else { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.MakeMethodIterator, GetDiagnosticSpan(newDeclaration, EditKind.Insert))); } } ReportLambdaAndClosureRudeEdits( oldModel, oldBody, newModel, newBody, newSymbol, lazyActiveOrMatchedLambdas, map, capabilities, diagnostics, out var newBodyHasLambdas, cancellationToken); // We need to provide syntax map to the compiler if // 1) The new member has a active statement // The values of local variables declared or synthesized in the method have to be preserved. // 2) The new member generates a state machine // In case the state machine is suspended we need to preserve variables. // 3) The new member contains lambdas // We need to map new lambdas in the method to the matching old ones. // If the old method has lambdas but the new one doesn't there is nothing to preserve. // 4) Constructor that emits initializers is updated. // We create syntax map even if it's not necessary: if any data member initializers are active/contain lambdas. // Since initializers are usually simple the map should not be large enough to make it worth optimizing it away. if (!activeNodes.IsEmpty() || newHasStateMachineSuspensionPoint || newBodyHasLambdas || IsConstructorWithMemberInitializers(newDeclaration) || IsDeclarationWithInitializer(oldDeclaration) || IsDeclarationWithInitializer(newDeclaration)) { syntaxMap = CreateSyntaxMap(map.Reverse); } foreach (var activeNode in activeNodes) { var activeStatementIndex = activeNode.ActiveStatementIndex; var hasMatching = false; var isNonLeaf = oldActiveStatements[activeStatementIndex].Statement.IsNonLeaf; var isPartiallyExecuted = (oldActiveStatements[activeStatementIndex].Statement.Flags & ActiveStatementFlags.PartiallyExecuted) != 0; var statementPart = activeNode.StatementPart; var oldStatementSyntax = activeNode.OldNode; var oldEnclosingLambdaBody = activeNode.EnclosingLambdaBody; newExceptionRegions[activeStatementIndex] = ImmutableArray<SourceFileSpan>.Empty; TextSpan newSpan; SyntaxNode? newStatementSyntax; Match<SyntaxNode>? match; if (oldEnclosingLambdaBody == null) { match = bodyMatch; hasMatching = TryMatchActiveStatement(oldStatementSyntax, statementPart, oldBody, newBody, out newStatementSyntax) || match.TryGetNewNode(oldStatementSyntax, out newStatementSyntax); } else { RoslynDebug.Assert(lazyActiveOrMatchedLambdas != null); var oldLambdaInfo = lazyActiveOrMatchedLambdas[oldEnclosingLambdaBody]; var newEnclosingLambdaBody = oldLambdaInfo.NewBody; match = oldLambdaInfo.Match; if (match != null) { RoslynDebug.Assert(newEnclosingLambdaBody != null); // matching lambda has body hasMatching = TryMatchActiveStatement(oldStatementSyntax, statementPart, oldEnclosingLambdaBody, newEnclosingLambdaBody, out newStatementSyntax) || match.TryGetNewNode(oldStatementSyntax, out newStatementSyntax); } else { // Lambda match is null if lambdas can't be matched, // in such case we won't have active statement matched either. hasMatching = false; newStatementSyntax = null; } } if (hasMatching) { RoslynDebug.Assert(newStatementSyntax != null); RoslynDebug.Assert(match != null); // The matching node doesn't produce sequence points. // E.g. "const" keyword is inserted into a local variable declaration with an initializer. newSpan = FindClosestActiveSpan(newStatementSyntax, statementPart); if ((isNonLeaf || isPartiallyExecuted) && !AreEquivalentActiveStatements(oldStatementSyntax, newStatementSyntax, statementPart)) { // rude edit: non-leaf active statement changed diagnostics.Add(new RudeEditDiagnostic(isNonLeaf ? RudeEditKind.ActiveStatementUpdate : RudeEditKind.PartiallyExecutedActiveStatementUpdate, newSpan)); } // other statements around active statement: ReportOtherRudeEditsAroundActiveStatement(diagnostics, match, oldStatementSyntax, newStatementSyntax, isNonLeaf); } else if (match == null) { RoslynDebug.Assert(oldEnclosingLambdaBody != null); RoslynDebug.Assert(lazyActiveOrMatchedLambdas != null); newSpan = GetDeletedNodeDiagnosticSpan(oldEnclosingLambdaBody, bodyMatch, lazyActiveOrMatchedLambdas); // Lambda containing the active statement can't be found in the new source. var oldLambda = GetLambda(oldEnclosingLambdaBody); diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.ActiveStatementLambdaRemoved, newSpan, oldLambda, new[] { GetDisplayName(oldLambda) })); } else { newSpan = GetDeletedNodeActiveSpan(match.Matches, oldStatementSyntax); if (isNonLeaf || isPartiallyExecuted) { // rude edit: internal active statement deleted diagnostics.Add( new RudeEditDiagnostic(isNonLeaf ? RudeEditKind.DeleteActiveStatement : RudeEditKind.PartiallyExecutedActiveStatementDelete, GetDeletedNodeDiagnosticSpan(match.Matches, oldStatementSyntax), arguments: new[] { FeaturesResources.code })); } } // exception handling around the statement: CalculateExceptionRegionsAroundActiveStatement( bodyMatch, oldStatementSyntax, newStatementSyntax, newSpan, activeStatementIndex, isNonLeaf, newExceptionRegions, diagnostics, cancellationToken); // We have already calculated the new location of this active statement when analyzing another member declaration. // This may only happen when two or more member declarations share the same body (VB AsNew clause). Debug.Assert(IsDeclarationWithSharedBody(newDeclaration) || newActiveStatements[activeStatementIndex] == null); Debug.Assert(newSpan != default); newActiveStatements[activeStatementIndex] = GetActiveStatementWithSpan(oldActiveStatements[activeStatementIndex], newDeclaration.SyntaxTree, newSpan, diagnostics, cancellationToken); } } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { // Set the new spans of active statements overlapping the method body to match the old spans. // Even though these might be now outside of the method body it's ok since we report a rude edit and don't allow to continue. foreach (var i in activeStatementIndices) { newActiveStatements[i] = oldActiveStatements[i].Statement; newExceptionRegions[i] = ImmutableArray<SourceFileSpan>.Empty; } // We expect OOM to be thrown during the analysis if the number of statements is too large. // In such case we report a rude edit for the document. If the host is actually running out of memory, // it might throw another OOM here or later on. diagnostics.Add(new RudeEditDiagnostic( (e is OutOfMemoryException) ? RudeEditKind.MemberBodyTooBig : RudeEditKind.MemberBodyInternalError, GetBodyDiagnosticSpan(newBody, EditKind.Update), newBody, arguments: new[] { GetBodyDisplayName(newBody) })); } } private bool TryGetTrackedStatement(ImmutableArray<LinePositionSpan> activeStatementSpans, int index, SourceText text, SyntaxNode declaration, SyntaxNode body, [NotNullWhen(true)] out SyntaxNode? trackedStatement, out int trackedStatementPart) { trackedStatement = null; trackedStatementPart = -1; // Active statements are not tracked in this document (e.g. the file is closed). if (activeStatementSpans.IsEmpty) { return false; } var trackedLineSpan = activeStatementSpans[index]; if (trackedLineSpan == default) { return false; } var trackedSpan = text.Lines.GetTextSpan(trackedLineSpan); // The tracking span might have been deleted or moved outside of the member span. // It is not an error to move the statement - we just ignore it. // Consider: Instead of checking here, explicitly handle all cases when active statements can be outside of the body in FindStatement and // return false if the requested span is outside of the active envelope. var (envelope, hole) = GetActiveSpanEnvelope(declaration); if (!envelope.Contains(trackedSpan) || hole.Contains(trackedSpan)) { return false; } trackedStatement = FindStatement(body, trackedSpan, out trackedStatementPart); return true; } private ActiveStatement GetActiveStatementWithSpan(UnmappedActiveStatement oldStatement, SyntaxTree newTree, TextSpan newSpan, ArrayBuilder<RudeEditDiagnostic> diagnostics, CancellationToken cancellationToken) { var mappedLineSpan = newTree.GetMappedLineSpan(newSpan, cancellationToken); if (mappedLineSpan.HasMappedPath && mappedLineSpan.Path != oldStatement.Statement.FileSpan.Path) { // changing the source file of an active statement diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.UpdateAroundActiveStatement, newSpan, LineDirectiveSyntaxKind, arguments: new[] { string.Format(FeaturesResources._0_directive, LineDirectiveKeyword) })); } return oldStatement.Statement.WithFileSpan(mappedLineSpan); } private void CalculateExceptionRegionsAroundActiveStatement( Match<SyntaxNode> bodyMatch, SyntaxNode oldStatementSyntax, SyntaxNode? newStatementSyntax, TextSpan newStatementSyntaxSpan, int ordinal, bool isNonLeaf, ImmutableArray<ImmutableArray<SourceFileSpan>>.Builder newExceptionRegions, ArrayBuilder<RudeEditDiagnostic> diagnostics, CancellationToken cancellationToken) { if (newStatementSyntax == null) { if (!bodyMatch.NewRoot.Span.Contains(newStatementSyntaxSpan.Start)) { return; } newStatementSyntax = bodyMatch.NewRoot.FindToken(newStatementSyntaxSpan.Start).Parent; Contract.ThrowIfNull(newStatementSyntax); } var oldAncestors = GetExceptionHandlingAncestors(oldStatementSyntax, isNonLeaf); var newAncestors = GetExceptionHandlingAncestors(newStatementSyntax, isNonLeaf); if (oldAncestors.Count > 0 || newAncestors.Count > 0) { var edits = bodyMatch.GetSequenceEdits(oldAncestors, newAncestors); ReportEnclosingExceptionHandlingRudeEdits(diagnostics, edits, oldStatementSyntax, newStatementSyntaxSpan); // Exception regions are not needed in presence of errors. if (diagnostics.Count == 0) { Debug.Assert(oldAncestors.Count == newAncestors.Count); newExceptionRegions[ordinal] = GetExceptionRegions(newAncestors, newStatementSyntax.SyntaxTree, cancellationToken).Spans; } } } /// <summary> /// Calculates a syntax map of the entire method body including all lambda bodies it contains (recursively). /// </summary> private BidirectionalMap<SyntaxNode> ComputeMap( Match<SyntaxNode> bodyMatch, ArrayBuilder<ActiveNode> activeNodes, ref Dictionary<SyntaxNode, LambdaInfo>? lazyActiveOrMatchedLambdas, ArrayBuilder<RudeEditDiagnostic> diagnostics) { ArrayBuilder<Match<SyntaxNode>>? lambdaBodyMatches = null; var currentLambdaBodyMatch = -1; var currentBodyMatch = bodyMatch; while (true) { foreach (var (oldNode, newNode) in currentBodyMatch.Matches) { // Skip root, only enumerate body matches. if (oldNode == currentBodyMatch.OldRoot) { Debug.Assert(newNode == currentBodyMatch.NewRoot); continue; } if (TryGetLambdaBodies(oldNode, out var oldLambdaBody1, out var oldLambdaBody2)) { lambdaBodyMatches ??= ArrayBuilder<Match<SyntaxNode>>.GetInstance(); lazyActiveOrMatchedLambdas ??= new Dictionary<SyntaxNode, LambdaInfo>(); var newLambdaBody1 = TryGetPartnerLambdaBody(oldLambdaBody1, newNode); if (newLambdaBody1 != null) { lambdaBodyMatches.Add(ComputeLambdaBodyMatch(oldLambdaBody1, newLambdaBody1, activeNodes, lazyActiveOrMatchedLambdas, diagnostics)); } if (oldLambdaBody2 != null) { var newLambdaBody2 = TryGetPartnerLambdaBody(oldLambdaBody2, newNode); if (newLambdaBody2 != null) { lambdaBodyMatches.Add(ComputeLambdaBodyMatch(oldLambdaBody2, newLambdaBody2, activeNodes, lazyActiveOrMatchedLambdas, diagnostics)); } } } } currentLambdaBodyMatch++; if (lambdaBodyMatches == null || currentLambdaBodyMatch == lambdaBodyMatches.Count) { break; } currentBodyMatch = lambdaBodyMatches[currentLambdaBodyMatch]; } if (lambdaBodyMatches == null) { return BidirectionalMap<SyntaxNode>.FromMatch(bodyMatch); } var map = new Dictionary<SyntaxNode, SyntaxNode>(); var reverseMap = new Dictionary<SyntaxNode, SyntaxNode>(); // include all matches, including the root: map.AddRange(bodyMatch.Matches); reverseMap.AddRange(bodyMatch.ReverseMatches); foreach (var lambdaBodyMatch in lambdaBodyMatches) { foreach (var pair in lambdaBodyMatch.Matches) { if (!map.ContainsKey(pair.Key)) { map[pair.Key] = pair.Value; reverseMap[pair.Value] = pair.Key; } } } lambdaBodyMatches?.Free(); return new BidirectionalMap<SyntaxNode>(map, reverseMap); } private Match<SyntaxNode> ComputeLambdaBodyMatch( SyntaxNode oldLambdaBody, SyntaxNode newLambdaBody, IReadOnlyList<ActiveNode> activeNodes, [Out] Dictionary<SyntaxNode, LambdaInfo> activeOrMatchedLambdas, [Out] ArrayBuilder<RudeEditDiagnostic> diagnostics) { ActiveNode[]? activeNodesInLambda; if (activeOrMatchedLambdas.TryGetValue(oldLambdaBody, out var info)) { // Lambda may be matched but not be active. activeNodesInLambda = info.ActiveNodeIndices?.Select(i => activeNodes[i]).ToArray(); } else { // If the lambda body isn't in the map it doesn't have any active/tracked statements. activeNodesInLambda = null; info = new LambdaInfo(); } var lambdaBodyMatch = ComputeBodyMatch(oldLambdaBody, newLambdaBody, activeNodesInLambda ?? Array.Empty<ActiveNode>(), diagnostics, out _, out _); activeOrMatchedLambdas[oldLambdaBody] = info.WithMatch(lambdaBodyMatch, newLambdaBody); return lambdaBodyMatch; } private Match<SyntaxNode> ComputeBodyMatch( SyntaxNode oldBody, SyntaxNode newBody, ActiveNode[] activeNodes, ArrayBuilder<RudeEditDiagnostic> diagnostics, out bool oldHasStateMachineSuspensionPoint, out bool newHasStateMachineSuspensionPoint) { List<KeyValuePair<SyntaxNode, SyntaxNode>>? lazyKnownMatches = null; List<SequenceEdit>? lazyRudeEdits = null; GetStateMachineInfo(oldBody, out var oldStateMachineSuspensionPoints, out var oldStateMachineKinds); GetStateMachineInfo(newBody, out var newStateMachineSuspensionPoints, out var newStateMachineKinds); AddMatchingActiveNodes(ref lazyKnownMatches, activeNodes); // Consider following cases: // 1) Both old and new methods contain yields/awaits. // Map the old suspension points to new ones, report errors for added/deleted suspension points. // 2) The old method contains yields/awaits but the new doesn't. // Report rude edits for each deleted yield/await. // 3) The new method contains yields/awaits but the old doesn't. // a) If the method has active statements report rude edits for each inserted yield/await (insert "around" an active statement). // b) If the method has no active statements then the edit is valid, we don't need to calculate map. // 4) The old method is async/iterator, the new method is not and it contains an active statement. // Report rude edit since we can't remap IP from MoveNext to the kickoff method. // Note that iterators in VB don't need to contain yield, so this case is not covered by change in number of yields. var creatingStateMachineAroundActiveStatement = oldStateMachineSuspensionPoints.Length == 0 && newStateMachineSuspensionPoints.Length > 0 && activeNodes.Length > 0; oldHasStateMachineSuspensionPoint = oldStateMachineSuspensionPoints.Length > 0; newHasStateMachineSuspensionPoint = newStateMachineSuspensionPoints.Length > 0; if (oldStateMachineSuspensionPoints.Length > 0 || creatingStateMachineAroundActiveStatement) { AddMatchingStateMachineSuspensionPoints(ref lazyKnownMatches, ref lazyRudeEdits, oldStateMachineSuspensionPoints, newStateMachineSuspensionPoints); } var match = ComputeBodyMatch(oldBody, newBody, lazyKnownMatches); if (IsLocalFunction(match.OldRoot) && IsLocalFunction(match.NewRoot)) { ReportLocalFunctionsDeclarationRudeEdits(diagnostics, match); } if (lazyRudeEdits != null) { foreach (var rudeEdit in lazyRudeEdits) { if (rudeEdit.Kind == EditKind.Delete) { var deletedNode = oldStateMachineSuspensionPoints[rudeEdit.OldIndex]; ReportStateMachineSuspensionPointDeletedRudeEdit(diagnostics, match, deletedNode); } else { Debug.Assert(rudeEdit.Kind == EditKind.Insert); var insertedNode = newStateMachineSuspensionPoints[rudeEdit.NewIndex]; ReportStateMachineSuspensionPointInsertedRudeEdit(diagnostics, match, insertedNode, creatingStateMachineAroundActiveStatement); } } } else if (oldStateMachineSuspensionPoints.Length > 0) { Debug.Assert(oldStateMachineSuspensionPoints.Length == newStateMachineSuspensionPoints.Length); for (var i = 0; i < oldStateMachineSuspensionPoints.Length; i++) { var oldNode = oldStateMachineSuspensionPoints[i]; var newNode = newStateMachineSuspensionPoints[i]; // changing yield return to yield break, await to await foreach, yield to await, etc. if (StateMachineSuspensionPointKindEquals(oldNode, newNode)) { Debug.Assert(StatementLabelEquals(oldNode, newNode)); } else { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingStateMachineShape, newNode.Span, newNode, new[] { GetSuspensionPointDisplayName(oldNode, EditKind.Update), GetSuspensionPointDisplayName(newNode, EditKind.Update) })); } ReportStateMachineSuspensionPointRudeEdits(diagnostics, oldNode, newNode); } } else if (activeNodes.Length > 0) { // It is allowed to update a regular method to an async method or an iterator. // The only restriction is a presence of an active statement in the method body // since the debugger does not support remapping active statements to a different method. if (oldStateMachineKinds != newStateMachineKinds) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, GetBodyDiagnosticSpan(newBody, EditKind.Update))); } } // report removing async as rude: if (lazyRudeEdits == null) { if ((oldStateMachineKinds & StateMachineKinds.Async) != 0 && (newStateMachineKinds & StateMachineKinds.Async) == 0) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingFromAsynchronousToSynchronous, GetBodyDiagnosticSpan(newBody, EditKind.Update), newBody, new[] { GetBodyDisplayName(newBody) })); } // VB supports iterator lambdas/methods without yields if ((oldStateMachineKinds & StateMachineKinds.Iterator) != 0 && (newStateMachineKinds & StateMachineKinds.Iterator) == 0) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ModifiersUpdate, GetBodyDiagnosticSpan(newBody, EditKind.Update), newBody, new[] { GetBodyDisplayName(newBody) })); } } return match; } internal virtual void ReportStateMachineSuspensionPointDeletedRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode deletedSuspensionPoint) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.Delete, GetDeletedNodeDiagnosticSpan(match.Matches, deletedSuspensionPoint), deletedSuspensionPoint, new[] { GetSuspensionPointDisplayName(deletedSuspensionPoint, EditKind.Delete) })); } internal virtual void ReportStateMachineSuspensionPointInsertedRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode insertedSuspensionPoint, bool aroundActiveStatement) { diagnostics.Add(new RudeEditDiagnostic( aroundActiveStatement ? RudeEditKind.InsertAroundActiveStatement : RudeEditKind.Insert, GetDiagnosticSpan(insertedSuspensionPoint, EditKind.Insert), insertedSuspensionPoint, new[] { GetSuspensionPointDisplayName(insertedSuspensionPoint, EditKind.Insert) })); } private static void AddMatchingActiveNodes(ref List<KeyValuePair<SyntaxNode, SyntaxNode>>? lazyKnownMatches, IEnumerable<ActiveNode> activeNodes) { // add nodes that are tracked by the editor buffer to known matches: foreach (var activeNode in activeNodes) { if (activeNode.NewTrackedNode != null) { lazyKnownMatches ??= new List<KeyValuePair<SyntaxNode, SyntaxNode>>(); lazyKnownMatches.Add(KeyValuePairUtil.Create(activeNode.OldNode, activeNode.NewTrackedNode)); } } } private void AddMatchingStateMachineSuspensionPoints( ref List<KeyValuePair<SyntaxNode, SyntaxNode>>? lazyKnownMatches, ref List<SequenceEdit>? lazyRudeEdits, ImmutableArray<SyntaxNode> oldStateMachineSuspensionPoints, ImmutableArray<SyntaxNode> newStateMachineSuspensionPoints) { // State machine suspension points (yield statements, await expressions, await foreach loops, await using declarations) // determine the structure of the generated state machine. // Change of the SM structure is far more significant then changes of the value (arguments) of these nodes. // Hence we build the match such that these nodes are fixed. lazyKnownMatches ??= new List<KeyValuePair<SyntaxNode, SyntaxNode>>(); void AddMatch(ref List<KeyValuePair<SyntaxNode, SyntaxNode>> lazyKnownMatches, int oldIndex, int newIndex) { var oldNode = oldStateMachineSuspensionPoints[oldIndex]; var newNode = newStateMachineSuspensionPoints[newIndex]; if (StatementLabelEquals(oldNode, newNode)) { lazyKnownMatches.Add(KeyValuePairUtil.Create(oldNode, newNode)); } } if (oldStateMachineSuspensionPoints.Length == newStateMachineSuspensionPoints.Length) { for (var i = 0; i < oldStateMachineSuspensionPoints.Length; i++) { AddMatch(ref lazyKnownMatches, i, i); } } else { // use LCS to provide better errors (deletes, inserts and updates) var edits = GetSyntaxSequenceEdits(oldStateMachineSuspensionPoints, newStateMachineSuspensionPoints); foreach (var edit in edits) { var editKind = edit.Kind; if (editKind == EditKind.Update) { AddMatch(ref lazyKnownMatches, edit.OldIndex, edit.NewIndex); } else { lazyRudeEdits ??= new List<SequenceEdit>(); lazyRudeEdits.Add(edit); } } Debug.Assert(lazyRudeEdits != null); } } public ActiveStatementExceptionRegions GetExceptionRegions(SyntaxNode syntaxRoot, TextSpan unmappedActiveStatementSpan, bool isNonLeaf, CancellationToken cancellationToken) { var token = syntaxRoot.FindToken(unmappedActiveStatementSpan.Start); var ancestors = GetExceptionHandlingAncestors(token.Parent!, isNonLeaf); return GetExceptionRegions(ancestors, syntaxRoot.SyntaxTree, cancellationToken); } private ActiveStatementExceptionRegions GetExceptionRegions(List<SyntaxNode> exceptionHandlingAncestors, SyntaxTree tree, CancellationToken cancellationToken) { if (exceptionHandlingAncestors.Count == 0) { return new ActiveStatementExceptionRegions(ImmutableArray<SourceFileSpan>.Empty, isActiveStatementCovered: false); } var isCovered = false; using var _ = ArrayBuilder<SourceFileSpan>.GetInstance(out var result); for (var i = exceptionHandlingAncestors.Count - 1; i >= 0; i--) { var span = GetExceptionHandlingRegion(exceptionHandlingAncestors[i], out var coversAllChildren); // TODO: https://github.com/dotnet/roslyn/issues/52971 // 1) Check that the span doesn't cross #line pragmas with different file mappings. // 2) Check that the mapped path does not change and report rude edits if it does. result.Add(tree.GetMappedLineSpan(span, cancellationToken)); // Exception regions describe regions of code that can't be edited. // If the span covers all the children nodes we don't need to descend further. if (coversAllChildren) { isCovered = true; break; } } return new ActiveStatementExceptionRegions(result.ToImmutable(), isCovered); } private TextSpan GetDeletedNodeDiagnosticSpan(SyntaxNode deletedLambdaBody, Match<SyntaxNode> match, Dictionary<SyntaxNode, LambdaInfo> lambdaInfos) { var oldLambdaBody = deletedLambdaBody; while (true) { var oldParentLambdaBody = FindEnclosingLambdaBody(match.OldRoot, GetLambda(oldLambdaBody)); if (oldParentLambdaBody == null) { return GetDeletedNodeDiagnosticSpan(match.Matches, oldLambdaBody); } if (lambdaInfos.TryGetValue(oldParentLambdaBody, out var lambdaInfo) && lambdaInfo.Match != null) { return GetDeletedNodeDiagnosticSpan(lambdaInfo.Match.Matches, oldLambdaBody); } oldLambdaBody = oldParentLambdaBody; } } private TextSpan FindClosestActiveSpan(SyntaxNode statement, int statementPart) { if (TryGetActiveSpan(statement, statementPart, minLength: statement.Span.Length, out var span)) { return span; } // The node doesn't have sequence points. // E.g. "const" keyword is inserted into a local variable declaration with an initializer. foreach (var (node, part) in EnumerateNearStatements(statement)) { if (part == -1) { return node.Span; } if (TryGetActiveSpan(node, part, minLength: 0, out span)) { return span; } } // This might occur in cases where we report rude edit, so the exact location of the active span doesn't matter. // For example, when a method expression body is removed in C#. return statement.Span; } internal TextSpan GetDeletedNodeActiveSpan(IReadOnlyDictionary<SyntaxNode, SyntaxNode> forwardMap, SyntaxNode deletedNode) { foreach (var (oldNode, part) in EnumerateNearStatements(deletedNode)) { if (part == -1) { break; } if (forwardMap.TryGetValue(oldNode, out var newNode)) { return FindClosestActiveSpan(newNode, part); } } return GetDeletedNodeDiagnosticSpan(forwardMap, deletedNode); } internal TextSpan GetDeletedNodeDiagnosticSpan(IReadOnlyDictionary<SyntaxNode, SyntaxNode> forwardMap, SyntaxNode deletedNode) { var hasAncestor = TryGetMatchingAncestor(forwardMap, deletedNode, out var newAncestor); RoslynDebug.Assert(hasAncestor && newAncestor != null); return GetDiagnosticSpan(newAncestor, EditKind.Delete); } /// <summary> /// Finds the inner-most ancestor of the specified node that has a matching node in the new tree. /// </summary> private static bool TryGetMatchingAncestor(IReadOnlyDictionary<SyntaxNode, SyntaxNode> forwardMap, SyntaxNode? oldNode, [NotNullWhen(true)] out SyntaxNode? newAncestor) { while (oldNode != null) { if (forwardMap.TryGetValue(oldNode, out newAncestor)) { return true; } oldNode = oldNode.Parent; } // only happens if original oldNode is a root, // otherwise we always find a matching ancestor pair (roots). newAncestor = null; return false; } private IEnumerable<int> GetOverlappingActiveStatements(SyntaxNode declaration, ImmutableArray<UnmappedActiveStatement> statements) { var (envelope, hole) = GetActiveSpanEnvelope(declaration); if (envelope == default) { yield break; } var range = ActiveStatementsMap.GetSpansStartingInSpan( envelope.Start, envelope.End, statements, startPositionComparer: (x, y) => x.UnmappedSpan.Start.CompareTo(y)); for (var i = range.Start.Value; i < range.End.Value; i++) { if (!hole.Contains(statements[i].UnmappedSpan.Start)) { yield return i; } } } protected static bool HasParentEdit(IReadOnlyDictionary<SyntaxNode, EditKind> editMap, Edit<SyntaxNode> edit) { SyntaxNode node; switch (edit.Kind) { case EditKind.Insert: node = edit.NewNode; break; case EditKind.Delete: node = edit.OldNode; break; default: return false; } return HasEdit(editMap, node.Parent, edit.Kind); } protected static bool HasEdit(IReadOnlyDictionary<SyntaxNode, EditKind> editMap, SyntaxNode? node, EditKind editKind) { return node is object && editMap.TryGetValue(node, out var parentEdit) && parentEdit == editKind; } #endregion #region Rude Edits around Active Statement protected void AddAroundActiveStatementRudeDiagnostic(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode? oldNode, SyntaxNode? newNode, TextSpan newActiveStatementSpan) { if (oldNode == null) { RoslynDebug.Assert(newNode != null); AddRudeInsertAroundActiveStatement(diagnostics, newNode); } else if (newNode == null) { RoslynDebug.Assert(oldNode != null); AddRudeDeleteAroundActiveStatement(diagnostics, oldNode, newActiveStatementSpan); } else { AddRudeUpdateAroundActiveStatement(diagnostics, newNode); } } protected void AddRudeUpdateAroundActiveStatement(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode newNode) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.UpdateAroundActiveStatement, GetDiagnosticSpan(newNode, EditKind.Update), newNode, new[] { GetDisplayName(newNode, EditKind.Update) })); } protected void AddRudeInsertAroundActiveStatement(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode newNode) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.InsertAroundActiveStatement, GetDiagnosticSpan(newNode, EditKind.Insert), newNode, new[] { GetDisplayName(newNode, EditKind.Insert) })); } protected void AddRudeDeleteAroundActiveStatement(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldNode, TextSpan newActiveStatementSpan) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.DeleteAroundActiveStatement, newActiveStatementSpan, oldNode, new[] { GetDisplayName(oldNode, EditKind.Delete) })); } protected void ReportUnmatchedStatements<TSyntaxNode>( ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, Func<SyntaxNode, bool> nodeSelector, SyntaxNode oldActiveStatement, SyntaxNode newActiveStatement, Func<TSyntaxNode, TSyntaxNode, bool> areEquivalent, Func<TSyntaxNode, TSyntaxNode, bool>? areSimilar) where TSyntaxNode : SyntaxNode { var newNodes = GetAncestors(GetEncompassingAncestor(match.NewRoot), newActiveStatement, nodeSelector); if (newNodes == null) { return; } var oldNodes = GetAncestors(GetEncompassingAncestor(match.OldRoot), oldActiveStatement, nodeSelector); int matchCount; if (oldNodes != null) { matchCount = MatchNodes(oldNodes, newNodes, diagnostics: null, match: match, comparer: areEquivalent); // Do another pass over the nodes to improve error messages. if (areSimilar != null && matchCount < Math.Min(oldNodes.Count, newNodes.Count)) { matchCount += MatchNodes(oldNodes, newNodes, diagnostics: diagnostics, match: null, comparer: areSimilar); } } else { matchCount = 0; } if (matchCount < newNodes.Count) { ReportRudeEditsAndInserts(oldNodes, newNodes, diagnostics); } } private void ReportRudeEditsAndInserts(List<SyntaxNode?>? oldNodes, List<SyntaxNode?> newNodes, ArrayBuilder<RudeEditDiagnostic> diagnostics) { var oldNodeCount = (oldNodes != null) ? oldNodes.Count : 0; for (var i = 0; i < newNodes.Count; i++) { var newNode = newNodes[i]; if (newNode != null) { // Any difference can be expressed as insert, delete & insert, edit, or move & edit. // Heuristic: If the nesting levels of the old and new nodes are the same we report an edit. // Otherwise we report an insert. if (i < oldNodeCount && oldNodes![i] != null) { AddRudeUpdateAroundActiveStatement(diagnostics, newNode); } else { AddRudeInsertAroundActiveStatement(diagnostics, newNode); } } } } private int MatchNodes<TSyntaxNode>( List<SyntaxNode?> oldNodes, List<SyntaxNode?> newNodes, ArrayBuilder<RudeEditDiagnostic>? diagnostics, Match<SyntaxNode>? match, Func<TSyntaxNode, TSyntaxNode, bool> comparer) where TSyntaxNode : SyntaxNode { var matchCount = 0; var oldIndex = 0; for (var newIndex = 0; newIndex < newNodes.Count; newIndex++) { var newNode = newNodes[newIndex]; if (newNode == null) { continue; } SyntaxNode? oldNode; while (oldIndex < oldNodes.Count) { oldNode = oldNodes[oldIndex]; if (oldNode != null) { break; } // node has already been matched with a previous new node: oldIndex++; } if (oldIndex == oldNodes.Count) { break; } var i = -1; if (match == null) { i = IndexOfEquivalent(newNode, oldNodes, oldIndex, comparer); } else if (match.TryGetOldNode(newNode, out var partner) && comparer((TSyntaxNode)partner, (TSyntaxNode)newNode)) { i = oldNodes.IndexOf(partner, oldIndex); } if (i >= 0) { // we have an update or an exact match: oldNodes[i] = null; newNodes[newIndex] = null; matchCount++; if (diagnostics != null) { AddRudeUpdateAroundActiveStatement(diagnostics, newNode); } } } return matchCount; } private static int IndexOfEquivalent<TSyntaxNode>(SyntaxNode newNode, List<SyntaxNode?> oldNodes, int startIndex, Func<TSyntaxNode, TSyntaxNode, bool> comparer) where TSyntaxNode : SyntaxNode { for (var i = startIndex; i < oldNodes.Count; i++) { var oldNode = oldNodes[i]; if (oldNode != null && comparer((TSyntaxNode)oldNode, (TSyntaxNode)newNode)) { return i; } } return -1; } private static List<SyntaxNode?>? GetAncestors(SyntaxNode? root, SyntaxNode node, Func<SyntaxNode, bool> nodeSelector) { List<SyntaxNode?>? list = null; var current = node; while (current is object && current != root) { if (nodeSelector(current)) { list ??= new List<SyntaxNode?>(); list.Add(current); } current = current.Parent; } list?.Reverse(); return list; } #endregion #region Trivia Analysis /// <summary> /// Top-level edit script does not contain edits for a member if only trivia changed in its body. /// It also does not reflect changes in line mapping directives. /// Members that are unchanged but their location in the file changes are not considered updated. /// This method calculates line and trivia edits for all these cases. /// /// The resulting line edits are grouped by mapped document path and sorted by <see cref="SourceLineUpdate.OldLine"/> in each group. /// </summary> private void AnalyzeTrivia( Match<SyntaxNode> topMatch, IReadOnlyDictionary<SyntaxNode, EditKind> editMap, [Out] ArrayBuilder<(SyntaxNode OldNode, SyntaxNode NewNode, TextSpan DiagnosticSpan)> triviaEdits, [Out] ArrayBuilder<SequencePointUpdates> lineEdits, CancellationToken cancellationToken) { var oldTree = topMatch.OldRoot.SyntaxTree; var newTree = topMatch.NewRoot.SyntaxTree; // note: range [oldStartLine, oldEndLine] is end-inclusive using var _ = ArrayBuilder<(string filePath, int oldStartLine, int oldEndLine, int delta, SyntaxNode oldNode, SyntaxNode newNode)>.GetInstance(out var segments); foreach (var (oldNode, newNode) in topMatch.Matches) { cancellationToken.ThrowIfCancellationRequested(); if (editMap.ContainsKey(newNode)) { // Updated or inserted members will be (re)generated and don't need line edits. Debug.Assert(editMap[newNode] is EditKind.Update or EditKind.Insert); continue; } var newTokens = TryGetActiveTokens(newNode); if (newTokens == null) { continue; } // A (rude) edit could have been made that changes whether the node may contain active statements, // so although the nodes match they might not have the same active tokens. // E.g. field declaration changed to const field declaration. var oldTokens = TryGetActiveTokens(oldNode); if (oldTokens == null) { continue; } var newTokensEnum = newTokens.GetEnumerator(); var oldTokensEnum = oldTokens.GetEnumerator(); // We enumerate tokens of the body and split them into segments. // Each segment has sequence points mapped to the same file and also all lines the segment covers map to the same line delta. // The first token of a segment must be the first token that starts on the line. If the first segment token was in the middle line // the previous token on the same line would have different line delta and we wouldn't be able to map both of them at the same time. // All segments are included in the segments list regardless of their line delta (even when it's 0 - i.e. the lines did not change). // This is necessary as we need to detect collisions of multiple segments with different deltas later on. var lastNewToken = default(SyntaxToken); var lastOldStartLine = -1; var lastOldFilePath = (string?)null; var requiresUpdate = false; var firstSegmentIndex = segments.Count; var currentSegment = (path: (string?)null, oldStartLine: 0, delta: 0, firstOldNode: (SyntaxNode?)null, firstNewNode: (SyntaxNode?)null); var rudeEditSpan = default(TextSpan); // Check if the breakpoint span that covers the first node of the segment can be translated from the old to the new by adding a line delta. // If not we need to recompile the containing member since we are not able to produce line update for it. // The first node of the segment can be the first node on its line but the breakpoint span might start on the previous line. bool IsCurrentSegmentBreakpointSpanMappable() { var oldNode = currentSegment.firstOldNode; var newNode = currentSegment.firstNewNode; Contract.ThrowIfNull(oldNode); Contract.ThrowIfNull(newNode); // Some nodes (e.g. const local declaration) may not be covered by a breakpoint span. if (!TryGetEnclosingBreakpointSpan(oldNode, oldNode.SpanStart, out var oldBreakpointSpan) || !TryGetEnclosingBreakpointSpan(newNode, newNode.SpanStart, out var newBreakpointSpan)) { return true; } var oldMappedBreakpointSpan = (SourceFileSpan)oldTree.GetMappedLineSpan(oldBreakpointSpan, cancellationToken); var newMappedBreakpointSpan = (SourceFileSpan)newTree.GetMappedLineSpan(newBreakpointSpan, cancellationToken); if (oldMappedBreakpointSpan.AddLineDelta(currentSegment.delta) == newMappedBreakpointSpan) { return true; } rudeEditSpan = newBreakpointSpan; return false; } void AddCurrentSegment() { Debug.Assert(currentSegment.path != null); Debug.Assert(lastOldStartLine >= 0); // segment it ends on the line where the previous token starts (lastOldStartLine) segments.Add((currentSegment.path, currentSegment.oldStartLine, lastOldStartLine, currentSegment.delta, oldNode, newNode)); } bool oldHasToken; bool newHasToken; while (true) { oldHasToken = oldTokensEnum.MoveNext(); newHasToken = newTokensEnum.MoveNext(); // no update edit => tokens must match: Debug.Assert(oldHasToken == newHasToken); if (!oldHasToken) { if (!IsCurrentSegmentBreakpointSpanMappable()) { requiresUpdate = true; } else { // add last segment of the method body: AddCurrentSegment(); } break; } var oldSpan = oldTokensEnum.Current.Span; var newSpan = newTokensEnum.Current.Span; var oldMappedSpan = oldTree.GetMappedLineSpan(oldSpan, cancellationToken); var newMappedSpan = newTree.GetMappedLineSpan(newSpan, cancellationToken); var oldStartLine = oldMappedSpan.Span.Start.Line; var newStartLine = newMappedSpan.Span.Start.Line; var lineDelta = newStartLine - oldStartLine; // If any tokens in the method change their mapped column or mapped path the method must be recompiled // since the Debugger/SymReader does not support these updates. if (oldMappedSpan.Span.Start.Character != newMappedSpan.Span.Start.Character) { requiresUpdate = true; break; } if (currentSegment.path != oldMappedSpan.Path || currentSegment.delta != lineDelta) { // end of segment: if (currentSegment.path != null) { // Previous token start line is the same as this token start line, but the previous token line delta is not the same. // We can't therefore map the old start line to a new one using line delta since that would affect both tokens the same. if (lastOldStartLine == oldStartLine && string.Equals(lastOldFilePath, oldMappedSpan.Path)) { requiresUpdate = true; break; } if (!IsCurrentSegmentBreakpointSpanMappable()) { requiresUpdate = true; break; } // add current segment: AddCurrentSegment(); } // start new segment: currentSegment = (oldMappedSpan.Path, oldStartLine, lineDelta, oldTokensEnum.Current.Parent, newTokensEnum.Current.Parent); } lastNewToken = newTokensEnum.Current; lastOldStartLine = oldStartLine; lastOldFilePath = oldMappedSpan.Path; } // All tokens of a member body have been processed now. if (requiresUpdate) { // report the rude edit for the span of tokens that forced recompilation: if (rudeEditSpan.IsEmpty) { rudeEditSpan = TextSpan.FromBounds( lastNewToken.HasTrailingTrivia ? lastNewToken.Span.End : newTokensEnum.Current.FullSpan.Start, newTokensEnum.Current.SpanStart); } triviaEdits.Add((oldNode, newNode, rudeEditSpan)); // remove all segments added for the current member body: segments.Count = firstSegmentIndex; } } if (segments.Count == 0) { return; } // sort segments by file and then by start line: segments.Sort((x, y) => { var result = string.CompareOrdinal(x.filePath, y.filePath); return (result != 0) ? result : x.oldStartLine.CompareTo(y.oldStartLine); }); // Calculate line updates based on segments. // If two segments with different line deltas overlap we need to recompile all overlapping members except for the first one. // The debugger does not apply line deltas to recompiled methods and hence we can chose to recompile either of the overlapping segments // and apply line delta to the others. // // The line delta is applied to the start line of a sequence point. If start lines of two sequence points mapped to the same location // before the delta is applied then they will point to the same location after the delta is applied. But that wouldn't be correct // if two different mappings required applying different deltas and thus different locations. // This also applies when two methods are on the same line in the old version and they move by different deltas. using var _1 = ArrayBuilder<SourceLineUpdate>.GetInstance(out var documentLineEdits); var currentDocumentPath = segments[0].filePath; var previousOldEndLine = -1; var previousLineDelta = 0; foreach (var segment in segments) { if (segment.filePath != currentDocumentPath) { // store results for the previous document: if (documentLineEdits.Count > 0) { lineEdits.Add(new SequencePointUpdates(currentDocumentPath, documentLineEdits.ToImmutableAndClear())); } // switch to the next document: currentDocumentPath = segment.filePath; previousOldEndLine = -1; previousLineDelta = 0; } else if (segment.oldStartLine <= previousOldEndLine && segment.delta != previousLineDelta) { // The segment overlaps the previous one that has a different line delta. We need to recompile the method. // The debugger filters out line deltas that correspond to recompiled methods so we don't need to. triviaEdits.Add((segment.oldNode, segment.newNode, segment.newNode.Span)); continue; } // If the segment being added does not start on the line immediately following the previous segment end line // we need to insert another line update that resets the delta to 0 for the lines following the end line. if (documentLineEdits.Count > 0 && segment.oldStartLine > previousOldEndLine + 1) { Debug.Assert(previousOldEndLine >= 0); documentLineEdits.Add(CreateZeroDeltaSourceLineUpdate(previousOldEndLine + 1)); previousLineDelta = 0; } // Skip segment that doesn't change line numbers - the line edit would have no effect. // It was only added to facilitate detection of overlap with other segments. // Also skip the segment if the last line update has the same line delta as // consecutive same line deltas has the same effect as a single one. if (segment.delta != 0 && segment.delta != previousLineDelta) { documentLineEdits.Add(new SourceLineUpdate(segment.oldStartLine, segment.oldStartLine + segment.delta)); } previousOldEndLine = segment.oldEndLine; previousLineDelta = segment.delta; } if (currentDocumentPath != null && documentLineEdits.Count > 0) { lineEdits.Add(new SequencePointUpdates(currentDocumentPath, documentLineEdits.ToImmutable())); } } // TODO: Currently the constructor SourceLineUpdate does not allow update with zero delta. // Workaround until the debugger updates. internal static SourceLineUpdate CreateZeroDeltaSourceLineUpdate(int line) { var result = new SourceLineUpdate(); // TODO: Currently the constructor SourceLineUpdate does not allow update with zero delta. // Workaround until the debugger updates. unsafe { Unsafe.Write(&result, ((long)line << 32) | (long)line); } return result; } #endregion #region Semantic Analysis private sealed class AssemblyEqualityComparer : IEqualityComparer<IAssemblySymbol?> { public static readonly IEqualityComparer<IAssemblySymbol?> Instance = new AssemblyEqualityComparer(); public bool Equals(IAssemblySymbol? x, IAssemblySymbol? y) { // Types defined in old source assembly need to be treated as equivalent to types in the new source assembly, // provided that they only differ in their containing assemblies. // // The old source symbol has the same identity as the new one. // Two distinct assembly symbols that are referenced by the compilations have to have distinct identities. // If the compilation has two metadata references whose identities unify the compiler de-dups them and only creates // a single PE symbol. Thus comparing assemblies by identity partitions them so that each partition // contains assemblies that originated from the same Gen0 assembly. return Equals(x?.Identity, y?.Identity); } public int GetHashCode(IAssemblySymbol? obj) => obj?.Identity.GetHashCode() ?? 0; } // Ignore tuple element changes, nullability and dynamic. These type changes do not affect runtime type. // They only affect custom attributes emitted on the members - all runtimes are expected to accept // custom attribute updates in metadata deltas, even if they do not have any observable effect. private static readonly SymbolEquivalenceComparer s_runtimeSymbolEqualityComparer = new( AssemblyEqualityComparer.Instance, distinguishRefFromOut: true, tupleNamesMustMatch: false, ignoreNullableAnnotations: true); private static readonly SymbolEquivalenceComparer s_exactSymbolEqualityComparer = new( AssemblyEqualityComparer.Instance, distinguishRefFromOut: true, tupleNamesMustMatch: true, ignoreNullableAnnotations: false); protected static bool SymbolsEquivalent(ISymbol oldSymbol, ISymbol newSymbol) => s_exactSymbolEqualityComparer.Equals(oldSymbol, newSymbol); protected static bool SignaturesEquivalent(ImmutableArray<IParameterSymbol> oldParameters, ITypeSymbol oldReturnType, ImmutableArray<IParameterSymbol> newParameters, ITypeSymbol newReturnType) => ParametersEquivalent(oldParameters, newParameters, exact: false) && s_runtimeSymbolEqualityComparer.Equals(oldReturnType, newReturnType); // TODO: should check ref, ref readonly, custom mods protected static bool ParametersEquivalent(ImmutableArray<IParameterSymbol> oldParameters, ImmutableArray<IParameterSymbol> newParameters, bool exact) => oldParameters.SequenceEqual(newParameters, exact, (oldParameter, newParameter, exact) => ParameterTypesEquivalent(oldParameter, newParameter, exact)); protected static bool CustomModifiersEquivalent(CustomModifier oldModifier, CustomModifier newModifier, bool exact) => oldModifier.IsOptional == newModifier.IsOptional && TypesEquivalent(oldModifier.Modifier, newModifier.Modifier, exact); protected static bool CustomModifiersEquivalent(ImmutableArray<CustomModifier> oldModifiers, ImmutableArray<CustomModifier> newModifiers, bool exact) => oldModifiers.SequenceEqual(newModifiers, exact, (x, y, exact) => CustomModifiersEquivalent(x, y, exact)); protected static bool ReturnTypesEquivalent(IMethodSymbol oldMethod, IMethodSymbol newMethod, bool exact) => oldMethod.ReturnsByRef == newMethod.ReturnsByRef && oldMethod.ReturnsByRefReadonly == newMethod.ReturnsByRefReadonly && CustomModifiersEquivalent(oldMethod.ReturnTypeCustomModifiers, newMethod.ReturnTypeCustomModifiers, exact) && CustomModifiersEquivalent(oldMethod.RefCustomModifiers, newMethod.RefCustomModifiers, exact) && TypesEquivalent(oldMethod.ReturnType, newMethod.ReturnType, exact); protected static bool ReturnTypesEquivalent(IPropertySymbol oldProperty, IPropertySymbol newProperty, bool exact) => oldProperty.ReturnsByRef == newProperty.ReturnsByRef && oldProperty.ReturnsByRefReadonly == newProperty.ReturnsByRefReadonly && CustomModifiersEquivalent(oldProperty.TypeCustomModifiers, newProperty.TypeCustomModifiers, exact) && CustomModifiersEquivalent(oldProperty.RefCustomModifiers, newProperty.RefCustomModifiers, exact) && TypesEquivalent(oldProperty.Type, newProperty.Type, exact); protected static bool ReturnTypesEquivalent(IEventSymbol oldEvent, IEventSymbol newEvent, bool exact) => TypesEquivalent(oldEvent.Type, newEvent.Type, exact); // Note: SignatureTypeEquivalenceComparer compares dynamic and object the same. protected static bool TypesEquivalent(ITypeSymbol? oldType, ITypeSymbol? newType, bool exact) => (exact ? s_exactSymbolEqualityComparer : (IEqualityComparer<ITypeSymbol?>)s_runtimeSymbolEqualityComparer.SignatureTypeEquivalenceComparer).Equals(oldType, newType); protected static bool TypesEquivalent<T>(ImmutableArray<T> oldTypes, ImmutableArray<T> newTypes, bool exact) where T : ITypeSymbol => oldTypes.SequenceEqual(newTypes, exact, (x, y, exact) => TypesEquivalent(x, y, exact)); protected static bool ParameterTypesEquivalent(IParameterSymbol oldParameter, IParameterSymbol newParameter, bool exact) => (exact ? s_exactSymbolEqualityComparer : s_runtimeSymbolEqualityComparer).ParameterEquivalenceComparer.Equals(oldParameter, newParameter); protected static bool TypeParameterConstraintsEquivalent(ITypeParameterSymbol oldParameter, ITypeParameterSymbol newParameter, bool exact) => TypesEquivalent(oldParameter.ConstraintTypes, newParameter.ConstraintTypes, exact) && oldParameter.HasReferenceTypeConstraint == newParameter.HasReferenceTypeConstraint && oldParameter.HasValueTypeConstraint == newParameter.HasValueTypeConstraint && oldParameter.HasConstructorConstraint == newParameter.HasConstructorConstraint && oldParameter.HasNotNullConstraint == newParameter.HasNotNullConstraint && oldParameter.HasUnmanagedTypeConstraint == newParameter.HasUnmanagedTypeConstraint && oldParameter.Variance == newParameter.Variance; protected static bool TypeParametersEquivalent(ImmutableArray<ITypeParameterSymbol> oldParameters, ImmutableArray<ITypeParameterSymbol> newParameters, bool exact) => oldParameters.SequenceEqual(newParameters, exact, (oldParameter, newParameter, exact) => oldParameter.Name == newParameter.Name && TypeParameterConstraintsEquivalent(oldParameter, newParameter, exact)); protected static bool BaseTypesEquivalent(INamedTypeSymbol oldType, INamedTypeSymbol newType, bool exact) => TypesEquivalent(oldType.BaseType, newType.BaseType, exact) && TypesEquivalent(oldType.AllInterfaces, newType.AllInterfaces, exact); protected static bool MemberSignaturesEquivalent( ISymbol? oldMember, ISymbol? newMember, Func<ImmutableArray<IParameterSymbol>, ITypeSymbol, ImmutableArray<IParameterSymbol>, ITypeSymbol, bool>? signatureComparer = null) { if (oldMember == newMember) { return true; } if (oldMember == null || newMember == null || oldMember.Kind != newMember.Kind) { return false; } signatureComparer ??= SignaturesEquivalent; switch (oldMember.Kind) { case SymbolKind.Field: var oldField = (IFieldSymbol)oldMember; var newField = (IFieldSymbol)newMember; return signatureComparer(ImmutableArray<IParameterSymbol>.Empty, oldField.Type, ImmutableArray<IParameterSymbol>.Empty, newField.Type); case SymbolKind.Property: var oldProperty = (IPropertySymbol)oldMember; var newProperty = (IPropertySymbol)newMember; return signatureComparer(oldProperty.Parameters, oldProperty.Type, newProperty.Parameters, newProperty.Type); case SymbolKind.Method: var oldMethod = (IMethodSymbol)oldMember; var newMethod = (IMethodSymbol)newMember; return signatureComparer(oldMethod.Parameters, oldMethod.ReturnType, newMethod.Parameters, newMethod.ReturnType); default: throw ExceptionUtilities.UnexpectedValue(oldMember.Kind); } } private readonly struct ConstructorEdit { public readonly INamedTypeSymbol OldType; /// <summary> /// Contains syntax maps for all changed data member initializers or constructor declarations (of constructors emitting initializers) /// in the currently analyzed document. The key is the declaration of the member. /// </summary> public readonly Dictionary<SyntaxNode, Func<SyntaxNode, SyntaxNode?>?> ChangedDeclarations; public ConstructorEdit(INamedTypeSymbol oldType) { OldType = oldType; ChangedDeclarations = new Dictionary<SyntaxNode, Func<SyntaxNode, SyntaxNode?>?>(); } } private async Task<ImmutableArray<SemanticEditInfo>> AnalyzeSemanticsAsync( EditScript<SyntaxNode> editScript, IReadOnlyDictionary<SyntaxNode, EditKind> editMap, ImmutableArray<UnmappedActiveStatement> oldActiveStatements, ImmutableArray<LinePositionSpan> newActiveStatementSpans, IReadOnlyList<(SyntaxNode OldNode, SyntaxNode NewNode, TextSpan DiagnosticSpan)> triviaEdits, Project oldProject, Document? oldDocument, Document newDocument, SourceText newText, ArrayBuilder<RudeEditDiagnostic> diagnostics, ImmutableArray<ActiveStatement>.Builder newActiveStatements, ImmutableArray<ImmutableArray<SourceFileSpan>>.Builder newExceptionRegions, EditAndContinueCapabilities capabilities, bool inBreakState, CancellationToken cancellationToken) { Debug.Assert(inBreakState || newActiveStatementSpans.IsEmpty); if (editScript.Edits.Length == 0 && triviaEdits.Count == 0) { return ImmutableArray<SemanticEditInfo>.Empty; } // { new type -> constructor update } PooledDictionary<INamedTypeSymbol, ConstructorEdit>? instanceConstructorEdits = null; PooledDictionary<INamedTypeSymbol, ConstructorEdit>? staticConstructorEdits = null; var oldModel = (oldDocument != null) ? await oldDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false) : null; var newModel = await newDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var oldCompilation = oldModel?.Compilation ?? await oldProject.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false); var newCompilation = newModel.Compilation; using var _1 = PooledHashSet<ISymbol>.GetInstance(out var processedSymbols); using var _2 = ArrayBuilder<SemanticEditInfo>.GetInstance(out var semanticEdits); try { INamedTypeSymbol? lazyLayoutAttribute = null; foreach (var edit in editScript.Edits) { cancellationToken.ThrowIfCancellationRequested(); if (edit.Kind == EditKind.Move) { // Move is either a Rude Edit and already reported in syntax analysis, or has no semantic effect. // For example, in VB we allow move from field multi-declaration. // "Dim a, b As Integer" -> "Dim a As Integer" (update) and "Dim b As Integer" (move) continue; } if (edit.Kind == EditKind.Reorder) { // Currently we don't do any semantic checks for reordering // and we don't need to report them to the compiler either. // Consider: Currently symbol ordering changes are not reflected in metadata (Reflection will report original order). // Consider: Reordering of fields is not allowed since it changes the layout of the type. // This ordering should however not matter unless the type has explicit layout so we might want to allow it. // We do not check changes to the order if they occur across multiple documents (the containing type is partial). Debug.Assert(!IsDeclarationWithInitializer(edit.OldNode) && !IsDeclarationWithInitializer(edit.NewNode)); continue; } foreach (var symbolEdits in GetSymbolEdits(edit.Kind, edit.OldNode, edit.NewNode, oldModel, newModel, editMap, cancellationToken)) { Func<SyntaxNode, SyntaxNode?>? syntaxMap; SemanticEditKind editKind; var (oldSymbol, newSymbol, syntacticEditKind) = symbolEdits; var symbol = newSymbol ?? oldSymbol; Contract.ThrowIfNull(symbol); if (!processedSymbols.Add(symbol)) { continue; } var symbolKey = SymbolKey.Create(symbol, cancellationToken); // Ignore ambiguous resolution result - it may happen if there are semantic errors in the compilation. oldSymbol ??= symbolKey.Resolve(oldCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; newSymbol ??= symbolKey.Resolve(newCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; var (oldDeclaration, newDeclaration) = GetSymbolDeclarationNodes(oldSymbol, newSymbol, edit.OldNode, edit.NewNode); // The syntax change implies an update of the associated symbol but the old/new symbol does not actually exist. // Treat the edit as Insert/Delete. This may happen e.g. when all C# global statements are removed, the first one is added or they are moved to another file. if (syntacticEditKind == EditKind.Update) { if (oldSymbol == null || oldDeclaration != null && oldDeclaration.SyntaxTree != oldModel?.SyntaxTree) { syntacticEditKind = EditKind.Insert; } else if (newSymbol == null || newDeclaration != null && newDeclaration.SyntaxTree != newModel.SyntaxTree) { syntacticEditKind = EditKind.Delete; } } if (!inBreakState) { // Delete/insert/update edit of a member of a reloadable type (including nested types) results in Replace edit of the containing type. // If a Delete edit is part of delete-insert operation (member moved to a different partial type declaration or to a different file) // skip producing Replace semantic edit for this Delete edit as one will be reported by the corresponding Insert edit. var oldContainingType = oldSymbol?.ContainingType; var newContainingType = newSymbol?.ContainingType; var containingType = newContainingType ?? oldContainingType; if (containingType != null && (syntacticEditKind != EditKind.Delete || newSymbol == null)) { var containingTypeSymbolKey = SymbolKey.Create(containingType, cancellationToken); oldContainingType ??= (INamedTypeSymbol?)containingTypeSymbolKey.Resolve(oldCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; newContainingType ??= (INamedTypeSymbol?)containingTypeSymbolKey.Resolve(newCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; if (oldContainingType != null && newContainingType != null && IsReloadable(oldContainingType)) { if (processedSymbols.Add(newContainingType)) { if (capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)) { semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Replace, containingTypeSymbolKey, syntaxMap: null, syntaxMapTree: null, IsPartialEdit(oldContainingType, newContainingType, editScript.Match.OldRoot.SyntaxTree, editScript.Match.NewRoot.SyntaxTree) ? containingTypeSymbolKey : null)); } else { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingReloadableTypeNotSupportedByRuntime, newContainingType, newDeclaration, cancellationToken); } } continue; } } var oldType = oldSymbol as INamedTypeSymbol; var newType = newSymbol as INamedTypeSymbol; // Deleting a reloadable type is a rude edit, reported the same as for non-reloadable. // Adding a reloadable type is a standard type addition (TODO: unless added to a reloadable type?). // Making reloadable attribute non-reloadable results in a new version of the type that is // not reloadable but does not update the old version in-place. if (syntacticEditKind != EditKind.Delete && oldType != null && newType != null && IsReloadable(oldType)) { if (symbol == newType || processedSymbols.Add(newType)) { if (oldType.Name != newType.Name) { // https://github.com/dotnet/roslyn/issues/54886 ReportUpdateRudeEdit(diagnostics, RudeEditKind.Renamed, newType, newDeclaration, cancellationToken); } else if (oldType.Arity != newType.Arity) { // https://github.com/dotnet/roslyn/issues/54881 ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingTypeParameters, newType, newDeclaration, cancellationToken); } else if (!capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingReloadableTypeNotSupportedByRuntime, newType, newDeclaration, cancellationToken); } else { semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Replace, symbolKey, syntaxMap: null, syntaxMapTree: null, IsPartialEdit(oldType, newType, editScript.Match.OldRoot.SyntaxTree, editScript.Match.NewRoot.SyntaxTree) ? symbolKey : null)); } } continue; } } switch (syntacticEditKind) { case EditKind.Delete: { Contract.ThrowIfNull(oldModel); Contract.ThrowIfNull(oldSymbol); Contract.ThrowIfNull(oldDeclaration); var activeStatementIndices = GetOverlappingActiveStatements(oldDeclaration, oldActiveStatements); var hasActiveStatement = activeStatementIndices.Any(); // TODO: if the member isn't a field/property we should return empty span. // We need to adjust the tracking span design and UpdateUneditedSpans to account for such empty spans. if (hasActiveStatement) { var newSpan = IsDeclarationWithInitializer(oldDeclaration) ? GetDeletedNodeActiveSpan(editScript.Match.Matches, oldDeclaration) : GetDeletedNodeDiagnosticSpan(editScript.Match.Matches, oldDeclaration); foreach (var index in activeStatementIndices) { Debug.Assert(newActiveStatements[index] is null); newActiveStatements[index] = GetActiveStatementWithSpan(oldActiveStatements[index], editScript.Match.NewRoot.SyntaxTree, newSpan, diagnostics, cancellationToken); newExceptionRegions[index] = ImmutableArray<SourceFileSpan>.Empty; } } syntaxMap = null; editKind = SemanticEditKind.Delete; // Check if the declaration has been moved from one document to another. if (newSymbol != null && !(newSymbol is IMethodSymbol newMethod && newMethod.IsPartialDefinition)) { // Symbol has actually not been deleted but rather moved to another document, another partial type declaration // or replaced with an implicitly generated one (e.g. parameterless constructor, auto-generated record methods, etc.) // Report rude edit if the deleted code contains active statements. // TODO (https://github.com/dotnet/roslyn/issues/51177): // Only report rude edit when replacing member with an implicit one if it has an active statement. // We might be able to support moving active members but we would need to // 1) Move AnalyzeChangedMemberBody from Insert to Delete // 2) Handle active statements that moved to a different document in ActiveStatementTrackingService // 3) The debugger's ManagedActiveStatementUpdate might need another field indicating the source file path. if (hasActiveStatement) { ReportDeletedMemberRudeEdit(diagnostics, oldSymbol, newCompilation, RudeEditKind.DeleteActiveStatement, cancellationToken); continue; } if (!newSymbol.IsImplicitlyDeclared) { // Ignore the delete. The new symbol is explicitly declared and thus there will be an insert edit that will issue a semantic update. // Note that this could also be the case for deleting properties of records, but they will be handled when we see // their accessors below. continue; } if (IsPropertyAccessorDeclarationMatchingPrimaryConstructorParameter(oldDeclaration, newSymbol.ContainingType, out var isFirst)) { // Defer a constructor edit to cover the property initializer changing DeferConstructorEdit(oldSymbol.ContainingType, newSymbol.ContainingType, newDeclaration: null, syntaxMap, oldSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); // If there was no body deleted then we are done since the compiler generated property also has no body if (TryGetDeclarationBody(oldDeclaration) is null) { continue; } // If there was a body, then the backing field of the property will be affected so we // need to issue edits for the synthezied members. // We only need to do this once though. if (isFirst) { AddEditsForSynthesizedRecordMembers(newCompilation, newSymbol.ContainingType, semanticEdits, cancellationToken); } } // If a constructor is deleted and replaced by an implicit one the update needs to aggregate updates to all data member initializers, // or if a property is deleted that is part of a records primary constructor, which is effectivelly moving from an explicit to implicit // initializer. if (IsConstructorWithMemberInitializers(oldDeclaration)) { processedSymbols.Remove(oldSymbol); DeferConstructorEdit(oldSymbol.ContainingType, newSymbol.ContainingType, newDeclaration: null, syntaxMap, oldSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); continue; } // there is no insert edit for an implicit declaration, therefore we need to issue an update: editKind = SemanticEditKind.Update; } else { var diagnosticSpan = GetDeletedNodeDiagnosticSpan(editScript.Match.Matches, oldDeclaration); // If we got here for a global statement then the actual edit is a delete of the synthesized Main method if (IsGlobalMain(oldSymbol)) { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.Delete, diagnosticSpan, edit.OldNode, new[] { GetDisplayName(edit.OldNode, EditKind.Delete) })); continue; } // If the associated member declaration (accessor -> property/indexer/event, parameter -> method) has also been deleted skip // the delete of the symbol as it will be deleted by the delete of the associated member. // // Associated member declarations must be in the same document as the symbol, so we don't need to resolve their symbol. // In some cases the symbol even can't be resolved unambiguously. Consider e.g. resolving a method with its parameter deleted - // we wouldn't know which overload to resolve to. if (TryGetAssociatedMemberDeclaration(oldDeclaration, out var oldAssociatedMemberDeclaration)) { if (HasEdit(editMap, oldAssociatedMemberDeclaration, EditKind.Delete)) { continue; } } else if (oldSymbol.ContainingType != null) { // Check if the symbol being deleted is a member of a type that's also being deleted. // If so, skip the member deletion and only report the containing symbol deletion. var containingSymbolKey = SymbolKey.Create(oldSymbol.ContainingType, cancellationToken); var newContainingSymbol = containingSymbolKey.Resolve(newCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; if (newContainingSymbol == null) { continue; } } // deleting symbol is not allowed diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.Delete, diagnosticSpan, oldDeclaration, new[] { string.Format(FeaturesResources.member_kind_and_name, GetDisplayName(oldDeclaration, EditKind.Delete), oldSymbol.ToDisplayString(diagnosticSpan.IsEmpty ? s_fullyQualifiedMemberDisplayFormat : s_unqualifiedMemberDisplayFormat)) })); continue; } } break; case EditKind.Insert: { Contract.ThrowIfNull(newModel); Contract.ThrowIfNull(newSymbol); Contract.ThrowIfNull(newDeclaration); syntaxMap = null; editKind = SemanticEditKind.Insert; INamedTypeSymbol? oldContainingType; var newContainingType = newSymbol.ContainingType; // Check if the declaration has been moved from one document to another. if (oldSymbol != null) { // Symbol has actually not been inserted but rather moved between documents or partial type declarations, // or is replacing an implicitly generated one (e.g. parameterless constructor, auto-generated record methods, etc.) oldContainingType = oldSymbol.ContainingType; if (oldSymbol.IsImplicitlyDeclared) { // If a user explicitly implements a member of a record then we want to issue an update, not an insert. if (oldSymbol.DeclaringSyntaxReferences.Length == 1) { Contract.ThrowIfNull(oldDeclaration); ReportDeclarationInsertDeleteRudeEdits(diagnostics, oldDeclaration, newDeclaration, oldSymbol, newSymbol, cancellationToken); if (IsPropertyAccessorDeclarationMatchingPrimaryConstructorParameter(newDeclaration, newContainingType, out var isFirst)) { // If there is no body declared we can skip it entirely because for a property accessor // it matches what the compiler would have previously implicitly implemented. if (TryGetDeclarationBody(newDeclaration) is null) { continue; } // If there was a body, then the backing field of the property will be affected so we // need to issue edits for the synthezied members. Only need to do it once. if (isFirst) { AddEditsForSynthesizedRecordMembers(newCompilation, newContainingType, semanticEdits, cancellationToken); } } editKind = SemanticEditKind.Update; } } else if (oldSymbol.DeclaringSyntaxReferences.Length == 1 && newSymbol.DeclaringSyntaxReferences.Length == 1) { Contract.ThrowIfNull(oldDeclaration); // Handles partial methods and explicitly implemented properties that implement positional parameters of records // We ignore partial method definition parts when processing edits (GetSymbolForEdit). // The only declaration in compilation without syntax errors that can have multiple declaring references is a type declaration. // We can therefore ignore any symbols that have more than one declaration. ReportTypeLayoutUpdateRudeEdits(diagnostics, newSymbol, newDeclaration, newModel, ref lazyLayoutAttribute); // Compare the old declaration syntax of the symbol with its new declaration and report rude edits // if it changed in any way that's not allowed. ReportDeclarationInsertDeleteRudeEdits(diagnostics, oldDeclaration, newDeclaration, oldSymbol, newSymbol, cancellationToken); var oldBody = TryGetDeclarationBody(oldDeclaration); if (oldBody != null) { // The old symbol's declaration syntax may be located in a different document than the old version of the current document. var oldSyntaxDocument = oldProject.Solution.GetRequiredDocument(oldDeclaration.SyntaxTree); var oldSyntaxModel = await oldSyntaxDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var oldSyntaxText = await oldSyntaxDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); var newBody = TryGetDeclarationBody(newDeclaration); // Skip analysis of active statements. We already report rude edit for removal of code containing // active statements in the old declaration and don't currently support moving active statements. AnalyzeChangedMemberBody( oldDeclaration, newDeclaration, oldBody, newBody, oldSyntaxModel, newModel, oldSymbol, newSymbol, newText, oldActiveStatements: ImmutableArray<UnmappedActiveStatement>.Empty, newActiveStatementSpans: ImmutableArray<LinePositionSpan>.Empty, capabilities: capabilities, newActiveStatements, newExceptionRegions, diagnostics, out syntaxMap, cancellationToken); } // If a constructor changes from including initializers to not including initializers // we don't need to aggregate syntax map from all initializers for the constructor update semantic edit. var isNewConstructorWithMemberInitializers = IsConstructorWithMemberInitializers(newDeclaration); var isDeclarationWithInitializer = IsDeclarationWithInitializer(oldDeclaration) || IsDeclarationWithInitializer(newDeclaration); var isRecordPrimaryConstructorParameter = IsRecordPrimaryConstructorParameter(oldDeclaration); if (isNewConstructorWithMemberInitializers || isDeclarationWithInitializer || isRecordPrimaryConstructorParameter) { if (isNewConstructorWithMemberInitializers) { processedSymbols.Remove(newSymbol); } if (isDeclarationWithInitializer) { AnalyzeSymbolUpdate(oldSymbol, newSymbol, edit.NewNode, newCompilation, editScript.Match, capabilities, diagnostics, semanticEdits, syntaxMap, cancellationToken); } DeferConstructorEdit(oldSymbol.ContainingType, newContainingType, newDeclaration, syntaxMap, newSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); // Don't add a separate semantic edit. // Updates of data members with initializers and constructors that emit initializers will be aggregated and added later. continue; } editKind = SemanticEditKind.Update; } else { editKind = SemanticEditKind.Update; } } else if (TryGetAssociatedMemberDeclaration(newDeclaration, out var newAssociatedMemberDeclaration) && HasEdit(editMap, newAssociatedMemberDeclaration, EditKind.Insert)) { // If the symbol is an accessor and the containing property/indexer/event declaration has also been inserted skip // the insert of the accessor as it will be inserted by the property/indexer/event. continue; } else if (newSymbol is IParameterSymbol || newSymbol is ITypeParameterSymbol) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.Insert, GetDiagnosticSpan(newDeclaration, EditKind.Insert), newDeclaration, arguments: new[] { GetDisplayName(newDeclaration, EditKind.Insert) })); continue; } else if (newContainingType != null && !IsGlobalMain(newSymbol)) { // The edit actually adds a new symbol into an existing or a new type. var containingSymbolKey = SymbolKey.Create(newContainingType, cancellationToken); oldContainingType = containingSymbolKey.Resolve(oldCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol as INamedTypeSymbol; if (oldContainingType != null && !CanAddNewMember(newSymbol, capabilities)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.InsertNotSupportedByRuntime, GetDiagnosticSpan(newDeclaration, EditKind.Insert), newDeclaration, arguments: new[] { GetDisplayName(newDeclaration, EditKind.Insert) })); } // Check rude edits for each member even if it is inserted into a new type. ReportInsertedMemberSymbolRudeEdits(diagnostics, newSymbol, newDeclaration, insertingIntoExistingContainingType: oldContainingType != null); if (oldContainingType == null) { // Insertion of a new symbol into a new type. // We'll produce a single insert edit for the entire type. continue; } // Report rude edits for changes to data member changes of a type with an explicit layout. // We disallow moving a data member of a partial type with explicit layout even when it actually does not change the layout. // We could compare the exact order of the members but the scenario is unlikely to occur. ReportTypeLayoutUpdateRudeEdits(diagnostics, newSymbol, newDeclaration, newModel, ref lazyLayoutAttribute); // If a property or field is added to a record then the implicit constructors change, // and we need to mark a number of other synthesized members as having changed. if (newSymbol is IPropertySymbol or IFieldSymbol && newContainingType.IsRecord) { DeferConstructorEdit(oldContainingType, newContainingType, newDeclaration, syntaxMap, newSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); AddEditsForSynthesizedRecordMembers(newCompilation, newContainingType, semanticEdits, cancellationToken); } } else { // adds a new top-level type, or a global statement where none existed before, which is // therefore inserting the <Program>$ type Contract.ThrowIfFalse(newSymbol is INamedTypeSymbol || IsGlobalMain(newSymbol)); if (!capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.InsertNotSupportedByRuntime, GetDiagnosticSpan(newDeclaration, EditKind.Insert), newDeclaration, arguments: new[] { GetDisplayName(newDeclaration, EditKind.Insert) })); } oldContainingType = null; ReportInsertedMemberSymbolRudeEdits(diagnostics, newSymbol, newDeclaration, insertingIntoExistingContainingType: false); } var isConstructorWithMemberInitializers = IsConstructorWithMemberInitializers(newDeclaration); if (isConstructorWithMemberInitializers || IsDeclarationWithInitializer(newDeclaration)) { Contract.ThrowIfNull(newContainingType); Contract.ThrowIfNull(oldContainingType); // TODO (bug https://github.com/dotnet/roslyn/issues/2504) if (isConstructorWithMemberInitializers && editKind == SemanticEditKind.Insert && IsPartial(newContainingType) && HasMemberInitializerContainingLambda(oldContainingType, newSymbol.IsStatic, cancellationToken)) { // rude edit: Adding a constructor to a type with a field or property initializer that contains an anonymous function diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, GetDiagnosticSpan(newDeclaration, EditKind.Insert))); break; } DeferConstructorEdit(oldContainingType, newContainingType, newDeclaration, syntaxMap, newSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); if (isConstructorWithMemberInitializers) { processedSymbols.Remove(newSymbol); } if (isConstructorWithMemberInitializers || editKind == SemanticEditKind.Update) { // Don't add a separate semantic edit. // Edits of data members with initializers and constructors that emit initializers will be aggregated and added later. continue; } // A semantic edit to create the field/property is gonna be added. Contract.ThrowIfFalse(editKind == SemanticEditKind.Insert); } } break; case EditKind.Update: { Contract.ThrowIfNull(oldModel); Contract.ThrowIfNull(newModel); Contract.ThrowIfNull(oldSymbol); Contract.ThrowIfNull(newSymbol); editKind = SemanticEditKind.Update; syntaxMap = null; // Partial type declarations and their type parameters. if (oldSymbol.DeclaringSyntaxReferences.Length != 1 && newSymbol.DeclaringSyntaxReferences.Length != 1) { break; } Contract.ThrowIfNull(oldDeclaration); Contract.ThrowIfNull(newDeclaration); var oldBody = TryGetDeclarationBody(oldDeclaration); if (oldBody != null) { var newBody = TryGetDeclarationBody(newDeclaration); AnalyzeChangedMemberBody( oldDeclaration, newDeclaration, oldBody, newBody, oldModel, newModel, oldSymbol, newSymbol, newText, oldActiveStatements, newActiveStatementSpans, capabilities, newActiveStatements, newExceptionRegions, diagnostics, out syntaxMap, cancellationToken); } // If a constructor changes from including initializers to not including initializers // we don't need to aggregate syntax map from all initializers for the constructor update semantic edit. var isConstructorWithMemberInitializers = IsConstructorWithMemberInitializers(newDeclaration); var isDeclarationWithInitializer = IsDeclarationWithInitializer(oldDeclaration) || IsDeclarationWithInitializer(newDeclaration); if (isConstructorWithMemberInitializers || isDeclarationWithInitializer) { if (isConstructorWithMemberInitializers) { processedSymbols.Remove(newSymbol); } if (isDeclarationWithInitializer) { AnalyzeSymbolUpdate(oldSymbol, newSymbol, edit.NewNode, newCompilation, editScript.Match, capabilities, diagnostics, semanticEdits, syntaxMap, cancellationToken); } DeferConstructorEdit(oldSymbol.ContainingType, newSymbol.ContainingType, newDeclaration, syntaxMap, newSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); // Don't add a separate semantic edit. // Updates of data members with initializers and constructors that emit initializers will be aggregated and added later. continue; } } break; default: throw ExceptionUtilities.UnexpectedValue(edit.Kind); } Contract.ThrowIfFalse(editKind is SemanticEditKind.Update or SemanticEditKind.Insert); if (editKind == SemanticEditKind.Update) { Contract.ThrowIfNull(oldSymbol); AnalyzeSymbolUpdate(oldSymbol, newSymbol, edit.NewNode, newCompilation, editScript.Match, capabilities, diagnostics, semanticEdits, syntaxMap, cancellationToken); if (newSymbol is INamedTypeSymbol or IFieldSymbol or IPropertySymbol or IEventSymbol or IParameterSymbol or ITypeParameterSymbol) { continue; } } semanticEdits.Add(new SemanticEditInfo(editKind, symbolKey, syntaxMap, syntaxMapTree: null, IsPartialEdit(oldSymbol, newSymbol, editScript.Match.OldRoot.SyntaxTree, editScript.Match.NewRoot.SyntaxTree) ? symbolKey : null)); } } foreach (var (oldEditNode, newEditNode, diagnosticSpan) in triviaEdits) { Contract.ThrowIfNull(oldModel); Contract.ThrowIfNull(newModel); foreach (var (oldSymbol, newSymbol, editKind) in GetSymbolEdits(EditKind.Update, oldEditNode, newEditNode, oldModel, newModel, editMap, cancellationToken)) { // Trivia edits are only calculated for member bodies and each member has a symbol. Contract.ThrowIfNull(newSymbol); Contract.ThrowIfNull(oldSymbol); if (!processedSymbols.Add(newSymbol)) { // symbol already processed continue; } var (oldDeclaration, newDeclaration) = GetSymbolDeclarationNodes(oldSymbol, newSymbol, oldEditNode, newEditNode); Contract.ThrowIfNull(oldDeclaration); Contract.ThrowIfNull(newDeclaration); var oldContainingType = oldSymbol.ContainingType; var newContainingType = newSymbol.ContainingType; Contract.ThrowIfNull(oldContainingType); Contract.ThrowIfNull(newContainingType); if (IsReloadable(oldContainingType)) { if (processedSymbols.Add(newContainingType)) { if (capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)) { var containingTypeSymbolKey = SymbolKey.Create(oldContainingType, cancellationToken); semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Replace, containingTypeSymbolKey, syntaxMap: null, syntaxMapTree: null, IsPartialEdit(oldContainingType, newContainingType, editScript.Match.OldRoot.SyntaxTree, editScript.Match.NewRoot.SyntaxTree) ? containingTypeSymbolKey : null)); } else { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingReloadableTypeNotSupportedByRuntime, newContainingType, newDeclaration, cancellationToken); } } continue; } // We need to provide syntax map to the compiler if the member is active (see member update above): var isActiveMember = GetOverlappingActiveStatements(oldDeclaration, oldActiveStatements).Any() || IsStateMachineMethod(oldDeclaration) || ContainsLambda(oldDeclaration); var syntaxMap = isActiveMember ? CreateSyntaxMapForEquivalentNodes(oldDeclaration, newDeclaration) : null; // only trivia changed: Contract.ThrowIfFalse(IsConstructorWithMemberInitializers(oldDeclaration) == IsConstructorWithMemberInitializers(newDeclaration)); Contract.ThrowIfFalse(IsDeclarationWithInitializer(oldDeclaration) == IsDeclarationWithInitializer(newDeclaration)); var isConstructorWithMemberInitializers = IsConstructorWithMemberInitializers(newDeclaration); var isDeclarationWithInitializer = IsDeclarationWithInitializer(newDeclaration); if (isConstructorWithMemberInitializers || isDeclarationWithInitializer) { // TODO: only create syntax map if any field initializers are active/contain lambdas or this is a partial type syntaxMap ??= CreateSyntaxMapForEquivalentNodes(oldDeclaration, newDeclaration); if (isConstructorWithMemberInitializers) { processedSymbols.Remove(newSymbol); } DeferConstructorEdit(oldContainingType, newContainingType, newDeclaration, syntaxMap, newSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); // Don't add a separate semantic edit. // Updates of data members with initializers and constructors that emit initializers will be aggregated and added later. continue; } ReportMemberBodyUpdateRudeEdits(diagnostics, newDeclaration, diagnosticSpan); // updating generic methods and types if (InGenericContext(oldSymbol, out var oldIsGenericMethod)) { var rudeEdit = oldIsGenericMethod ? RudeEditKind.GenericMethodTriviaUpdate : RudeEditKind.GenericTypeTriviaUpdate; diagnostics.Add(new RudeEditDiagnostic(rudeEdit, diagnosticSpan, newEditNode, new[] { GetDisplayName(newEditNode) })); continue; } var symbolKey = SymbolKey.Create(newSymbol, cancellationToken); semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, symbolKey, syntaxMap, syntaxMapTree: null, IsPartialEdit(oldSymbol, newSymbol, editScript.Match.OldRoot.SyntaxTree, editScript.Match.NewRoot.SyntaxTree) ? symbolKey : null)); } } if (instanceConstructorEdits != null) { AddConstructorEdits( instanceConstructorEdits, editScript.Match, oldModel, oldCompilation, newCompilation, processedSymbols, capabilities, isStatic: false, semanticEdits, diagnostics, cancellationToken); } if (staticConstructorEdits != null) { AddConstructorEdits( staticConstructorEdits, editScript.Match, oldModel, oldCompilation, newCompilation, processedSymbols, capabilities, isStatic: true, semanticEdits, diagnostics, cancellationToken); } } finally { instanceConstructorEdits?.Free(); staticConstructorEdits?.Free(); } return semanticEdits.Distinct(SemanticEditInfoComparer.Instance).ToImmutableArray(); // If the symbol has a single declaring reference use its syntax node for further analysis. // Some syntax edits may not be directly associated with the declarations. // For example, in VB an update to AsNew clause of a multi-variable field declaration results in update to multiple symbols associated // with the variable declaration. But we need to analyse each symbol's modified identifier separately. (SyntaxNode? oldDeclaration, SyntaxNode? newDeclaration) GetSymbolDeclarationNodes(ISymbol? oldSymbol, ISymbol? newSymbol, SyntaxNode? oldNode, SyntaxNode? newNode) { return ( (oldSymbol != null && oldSymbol.DeclaringSyntaxReferences.Length == 1) ? GetSymbolDeclarationSyntax(oldSymbol.DeclaringSyntaxReferences.Single(), cancellationToken) : oldNode, (newSymbol != null && newSymbol.DeclaringSyntaxReferences.Length == 1) ? GetSymbolDeclarationSyntax(newSymbol.DeclaringSyntaxReferences.Single(), cancellationToken) : newNode); } } private static bool IsReloadable(INamedTypeSymbol type) { var current = type; while (current != null) { foreach (var attributeData in current.GetAttributes()) { // We assume that the attribute System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute, if it exists, is well formed. // If not an error will be reported during EnC delta emit. if (attributeData.AttributeClass is { Name: CreateNewOnMetadataUpdateAttributeName, ContainingNamespace: { Name: "CompilerServices", ContainingNamespace: { Name: "Runtime", ContainingNamespace: { Name: "System" } } } }) { return true; } } current = current.BaseType; } return false; } private sealed class SemanticEditInfoComparer : IEqualityComparer<SemanticEditInfo> { public static SemanticEditInfoComparer Instance = new(); private static readonly IEqualityComparer<SymbolKey> s_symbolKeyComparer = SymbolKey.GetComparer(); public bool Equals([AllowNull] SemanticEditInfo x, [AllowNull] SemanticEditInfo y) => s_symbolKeyComparer.Equals(x.Symbol, y.Symbol); public int GetHashCode([DisallowNull] SemanticEditInfo obj) => obj.Symbol.GetHashCode(); } private void ReportUpdatedSymbolDeclarationRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol oldSymbol, ISymbol newSymbol, SyntaxNode? newNode, Compilation newCompilation, out bool hasGeneratedAttributeChange, out bool hasGeneratedReturnTypeAttributeChange, CancellationToken cancellationToken) { var rudeEdit = RudeEditKind.None; hasGeneratedAttributeChange = false; hasGeneratedReturnTypeAttributeChange = false; if (oldSymbol.Kind != newSymbol.Kind) { rudeEdit = (oldSymbol.Kind == SymbolKind.Field || newSymbol.Kind == SymbolKind.Field) ? RudeEditKind.FieldKindUpdate : RudeEditKind.Update; } else if (oldSymbol.Name != newSymbol.Name) { rudeEdit = RudeEditKind.Renamed; // specialize rude edit for accessors and conversion operators: if (oldSymbol is IMethodSymbol oldMethod && newSymbol is IMethodSymbol newMethod) { if (oldMethod.AssociatedSymbol != null && newMethod.AssociatedSymbol != null) { if (oldMethod.MethodKind != newMethod.MethodKind) { rudeEdit = RudeEditKind.AccessorKindUpdate; } else { // rude edit will be reported by the associated symbol rudeEdit = RudeEditKind.None; } } else if (oldMethod.MethodKind == MethodKind.Conversion) { rudeEdit = RudeEditKind.ModifiersUpdate; } } } if (oldSymbol.DeclaredAccessibility != newSymbol.DeclaredAccessibility) { rudeEdit = RudeEditKind.ChangingAccessibility; } if (oldSymbol.IsStatic != newSymbol.IsStatic || oldSymbol.IsVirtual != newSymbol.IsVirtual || oldSymbol.IsAbstract != newSymbol.IsAbstract || oldSymbol.IsOverride != newSymbol.IsOverride || oldSymbol.IsExtern != newSymbol.IsExtern) { // Do not report for accessors as the error will be reported on their associated symbol. if (oldSymbol is not IMethodSymbol { AssociatedSymbol: not null }) { rudeEdit = RudeEditKind.ModifiersUpdate; } } if (oldSymbol is IFieldSymbol oldField && newSymbol is IFieldSymbol newField) { if (oldField.IsConst != newField.IsConst || oldField.IsReadOnly != newField.IsReadOnly || oldField.IsVolatile != newField.IsVolatile) { rudeEdit = RudeEditKind.ModifiersUpdate; } // Report rude edit for updating const fields and values of enums. // The latter is only reported whne the enum underlying type does not change to avoid cascading rude edits. if (oldField.IsConst && newField.IsConst && !Equals(oldField.ConstantValue, newField.ConstantValue) && TypesEquivalent(oldField.ContainingType.EnumUnderlyingType, newField.ContainingType.EnumUnderlyingType, exact: false)) { rudeEdit = RudeEditKind.InitializerUpdate; } if (oldField.FixedSize != newField.FixedSize) { rudeEdit = RudeEditKind.FixedSizeFieldUpdate; } AnalyzeType(oldField.Type, newField.Type, ref rudeEdit, ref hasGeneratedAttributeChange); } else if (oldSymbol is IMethodSymbol oldMethod && newSymbol is IMethodSymbol newMethod) { if (oldMethod.IsReadOnly != newMethod.IsReadOnly) { rudeEdit = RudeEditKind.ModifiersUpdate; } if (oldMethod.IsInitOnly != newMethod.IsInitOnly) { rudeEdit = RudeEditKind.AccessorKindUpdate; } // Consider: Generalize to compare P/Invokes regardless of how they are defined (using attribute or Declare) if (oldMethod.MethodKind == MethodKind.DeclareMethod || newMethod.MethodKind == MethodKind.DeclareMethod) { var oldImportData = oldMethod.GetDllImportData(); var newImportData = newMethod.GetDllImportData(); if (oldImportData != null && newImportData != null) { // Declare method syntax can't change these. Debug.Assert(oldImportData.BestFitMapping == newImportData.BestFitMapping || oldImportData.CallingConvention == newImportData.CallingConvention || oldImportData.ExactSpelling == newImportData.ExactSpelling || oldImportData.SetLastError == newImportData.SetLastError || oldImportData.ThrowOnUnmappableCharacter == newImportData.ThrowOnUnmappableCharacter); if (oldImportData.ModuleName != newImportData.ModuleName) { rudeEdit = RudeEditKind.DeclareLibraryUpdate; } else if (oldImportData.EntryPointName != newImportData.EntryPointName) { rudeEdit = RudeEditKind.DeclareAliasUpdate; } else if (oldImportData.CharacterSet != newImportData.CharacterSet) { rudeEdit = RudeEditKind.ModifiersUpdate; } } else if (oldImportData is null != newImportData is null) { rudeEdit = RudeEditKind.ModifiersUpdate; } } // VB implements clause if (!oldMethod.ExplicitInterfaceImplementations.SequenceEqual(newMethod.ExplicitInterfaceImplementations, (x, y) => SymbolsEquivalent(x, y))) { rudeEdit = RudeEditKind.ImplementsClauseUpdate; } // VB handles clause if (!AreHandledEventsEqual(oldMethod, newMethod)) { rudeEdit = RudeEditKind.HandlesClauseUpdate; } // Check return type - do not report for accessors, their containing symbol will report the rude edits and attribute updates. if (rudeEdit == RudeEditKind.None && oldMethod.AssociatedSymbol == null && newMethod.AssociatedSymbol == null) { AnalyzeReturnType(oldMethod, newMethod, ref rudeEdit, ref hasGeneratedReturnTypeAttributeChange); } } else if (oldSymbol is INamedTypeSymbol oldType && newSymbol is INamedTypeSymbol newType) { if (oldType.TypeKind != newType.TypeKind || oldType.IsRecord != newType.IsRecord) // TODO: https://github.com/dotnet/roslyn/issues/51874 { rudeEdit = RudeEditKind.TypeKindUpdate; } else if (oldType.IsRefLikeType != newType.IsRefLikeType || oldType.IsReadOnly != newType.IsReadOnly) { rudeEdit = RudeEditKind.ModifiersUpdate; } if (rudeEdit == RudeEditKind.None) { AnalyzeBaseTypes(oldType, newType, ref rudeEdit, ref hasGeneratedAttributeChange); if (oldType.DelegateInvokeMethod != null) { Contract.ThrowIfNull(newType.DelegateInvokeMethod); AnalyzeReturnType(oldType.DelegateInvokeMethod, newType.DelegateInvokeMethod, ref rudeEdit, ref hasGeneratedReturnTypeAttributeChange); } } } else if (oldSymbol is IPropertySymbol oldProperty && newSymbol is IPropertySymbol newProperty) { AnalyzeReturnType(oldProperty, newProperty, ref rudeEdit, ref hasGeneratedReturnTypeAttributeChange); } else if (oldSymbol is IEventSymbol oldEvent && newSymbol is IEventSymbol newEvent) { // "readonly" modifier can only be applied on the event itself, not on its accessors. if (oldEvent.AddMethod != null && newEvent.AddMethod != null && oldEvent.AddMethod.IsReadOnly != newEvent.AddMethod.IsReadOnly || oldEvent.RemoveMethod != null && newEvent.RemoveMethod != null && oldEvent.RemoveMethod.IsReadOnly != newEvent.RemoveMethod.IsReadOnly) { rudeEdit = RudeEditKind.ModifiersUpdate; } else { AnalyzeReturnType(oldEvent, newEvent, ref rudeEdit, ref hasGeneratedReturnTypeAttributeChange); } } else if (oldSymbol is IParameterSymbol oldParameter && newSymbol is IParameterSymbol newParameter) { if (oldParameter.RefKind != newParameter.RefKind || oldParameter.IsParams != newParameter.IsParams || IsExtensionMethodThisParameter(oldParameter) != IsExtensionMethodThisParameter(newParameter)) { rudeEdit = RudeEditKind.ModifiersUpdate; } else if (oldParameter.HasExplicitDefaultValue != newParameter.HasExplicitDefaultValue || oldParameter.HasExplicitDefaultValue && !Equals(oldParameter.ExplicitDefaultValue, newParameter.ExplicitDefaultValue)) { rudeEdit = RudeEditKind.InitializerUpdate; } else { AnalyzeParameterType(oldParameter, newParameter, ref rudeEdit, ref hasGeneratedAttributeChange); } } else if (oldSymbol is ITypeParameterSymbol oldTypeParameter && newSymbol is ITypeParameterSymbol newTypeParameter) { AnalyzeTypeParameter(oldTypeParameter, newTypeParameter, ref rudeEdit, ref hasGeneratedAttributeChange); } // Do not report modifier update if type kind changed. if (rudeEdit == RudeEditKind.None && oldSymbol.IsSealed != newSymbol.IsSealed) { // Do not report for accessors as the error will be reported on their associated symbol. if (oldSymbol is not IMethodSymbol { AssociatedSymbol: not null }) { rudeEdit = RudeEditKind.ModifiersUpdate; } } if (rudeEdit != RudeEditKind.None) { // so we'll just use the last global statement in the file ReportUpdateRudeEdit(diagnostics, rudeEdit, oldSymbol, newSymbol, newNode, newCompilation, cancellationToken); } } private static void AnalyzeType(ITypeSymbol oldType, ITypeSymbol newType, ref RudeEditKind rudeEdit, ref bool hasGeneratedAttributeChange, RudeEditKind rudeEditKind = RudeEditKind.TypeUpdate) { if (!TypesEquivalent(oldType, newType, exact: true)) { if (TypesEquivalent(oldType, newType, exact: false)) { hasGeneratedAttributeChange = true; } else { rudeEdit = rudeEditKind; } } } private static void AnalyzeBaseTypes(INamedTypeSymbol oldType, INamedTypeSymbol newType, ref RudeEditKind rudeEdit, ref bool hasGeneratedAttributeChange) { if (oldType.EnumUnderlyingType != null && newType.EnumUnderlyingType != null) { if (!TypesEquivalent(oldType.EnumUnderlyingType, newType.EnumUnderlyingType, exact: true)) { if (TypesEquivalent(oldType.EnumUnderlyingType, newType.EnumUnderlyingType, exact: false)) { hasGeneratedAttributeChange = true; } else { rudeEdit = RudeEditKind.EnumUnderlyingTypeUpdate; } } } else if (!BaseTypesEquivalent(oldType, newType, exact: true)) { if (BaseTypesEquivalent(oldType, newType, exact: false)) { hasGeneratedAttributeChange = true; } else { rudeEdit = RudeEditKind.BaseTypeOrInterfaceUpdate; } } } private static void AnalyzeParameterType(IParameterSymbol oldParameter, IParameterSymbol newParameter, ref RudeEditKind rudeEdit, ref bool hasGeneratedAttributeChange) { if (!ParameterTypesEquivalent(oldParameter, newParameter, exact: true)) { if (ParameterTypesEquivalent(oldParameter, newParameter, exact: false)) { hasGeneratedAttributeChange = true; } else { rudeEdit = RudeEditKind.TypeUpdate; } } } private static void AnalyzeTypeParameter(ITypeParameterSymbol oldParameter, ITypeParameterSymbol newParameter, ref RudeEditKind rudeEdit, ref bool hasGeneratedAttributeChange) { if (!TypeParameterConstraintsEquivalent(oldParameter, newParameter, exact: true)) { if (TypeParameterConstraintsEquivalent(oldParameter, newParameter, exact: false)) { hasGeneratedAttributeChange = true; } else { rudeEdit = (oldParameter.Variance != newParameter.Variance) ? RudeEditKind.VarianceUpdate : RudeEditKind.ChangingConstraints; } } } private static void AnalyzeReturnType(IMethodSymbol oldMethod, IMethodSymbol newMethod, ref RudeEditKind rudeEdit, ref bool hasGeneratedReturnTypeAttributeChange) { if (!ReturnTypesEquivalent(oldMethod, newMethod, exact: true)) { if (ReturnTypesEquivalent(oldMethod, newMethod, exact: false)) { hasGeneratedReturnTypeAttributeChange = true; } else if (IsGlobalMain(oldMethod) || IsGlobalMain(newMethod)) { rudeEdit = RudeEditKind.ChangeImplicitMainReturnType; } else { rudeEdit = RudeEditKind.TypeUpdate; } } } private static void AnalyzeReturnType(IEventSymbol oldEvent, IEventSymbol newEvent, ref RudeEditKind rudeEdit, ref bool hasGeneratedReturnTypeAttributeChange) { if (!ReturnTypesEquivalent(oldEvent, newEvent, exact: true)) { if (ReturnTypesEquivalent(oldEvent, newEvent, exact: false)) { hasGeneratedReturnTypeAttributeChange = true; } else { rudeEdit = RudeEditKind.TypeUpdate; } } } private static void AnalyzeReturnType(IPropertySymbol oldProperty, IPropertySymbol newProperty, ref RudeEditKind rudeEdit, ref bool hasGeneratedReturnTypeAttributeChange) { if (!ReturnTypesEquivalent(oldProperty, newProperty, exact: true)) { if (ReturnTypesEquivalent(oldProperty, newProperty, exact: false)) { hasGeneratedReturnTypeAttributeChange = true; } else { rudeEdit = RudeEditKind.TypeUpdate; } } } private static bool IsExtensionMethodThisParameter(IParameterSymbol parameter) => parameter is { Ordinal: 0, ContainingSymbol: IMethodSymbol { IsExtensionMethod: true } }; private void AnalyzeSymbolUpdate( ISymbol oldSymbol, ISymbol newSymbol, SyntaxNode? newNode, Compilation newCompilation, Match<SyntaxNode> topMatch, EditAndContinueCapabilities capabilities, ArrayBuilder<RudeEditDiagnostic> diagnostics, ArrayBuilder<SemanticEditInfo> semanticEdits, Func<SyntaxNode, SyntaxNode?>? syntaxMap, CancellationToken cancellationToken) { // TODO: fails in VB on delegate parameter https://github.com/dotnet/roslyn/issues/53337 // Contract.ThrowIfFalse(newSymbol.IsImplicitlyDeclared == newDeclaration is null); ReportCustomAttributeRudeEdits(diagnostics, oldSymbol, newSymbol, newNode, newCompilation, capabilities, out var hasAttributeChange, out var hasReturnTypeAttributeChange, cancellationToken); ReportUpdatedSymbolDeclarationRudeEdits(diagnostics, oldSymbol, newSymbol, newNode, newCompilation, out var hasGeneratedAttributeChange, out var hasGeneratedReturnTypeAttributeChange, cancellationToken); hasAttributeChange |= hasGeneratedAttributeChange; hasReturnTypeAttributeChange |= hasGeneratedReturnTypeAttributeChange; if (hasAttributeChange || hasReturnTypeAttributeChange) { AddCustomAttributeSemanticEdits(semanticEdits, oldSymbol, newSymbol, topMatch, syntaxMap, hasAttributeChange, hasReturnTypeAttributeChange, cancellationToken); } // updating generic methods and types if (InGenericContext(oldSymbol, out var oldIsGenericMethod) || InGenericContext(newSymbol, out _)) { var rudeEdit = oldIsGenericMethod ? RudeEditKind.GenericMethodUpdate : RudeEditKind.GenericTypeUpdate; ReportUpdateRudeEdit(diagnostics, rudeEdit, newSymbol, newNode, cancellationToken); } } private static void AddCustomAttributeSemanticEdits( ArrayBuilder<SemanticEditInfo> semanticEdits, ISymbol oldSymbol, ISymbol newSymbol, Match<SyntaxNode> topMatch, Func<SyntaxNode, SyntaxNode?>? syntaxMap, bool hasAttributeChange, bool hasReturnTypeAttributeChange, CancellationToken cancellationToken) { // Most symbol types will automatically have an edit added, so we just need to handle a few if (newSymbol is INamedTypeSymbol { DelegateInvokeMethod: not null and var newDelegateInvokeMethod } newDelegateType) { if (hasAttributeChange) { semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, SymbolKey.Create(newDelegateType, cancellationToken), syntaxMap, syntaxMapTree: null, partialType: null)); } if (hasReturnTypeAttributeChange) { // attributes applied on return type of a delegate are applied to both Invoke and BeginInvoke methods semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, SymbolKey.Create(newDelegateInvokeMethod, cancellationToken), syntaxMap, syntaxMapTree: null, partialType: null)); AddDelegateBeginInvokeEdit(newDelegateType); } } else if (newSymbol is INamedTypeSymbol) { var symbolKey = SymbolKey.Create(newSymbol, cancellationToken); semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, symbolKey, syntaxMap, syntaxMapTree: null, IsPartialEdit(oldSymbol, newSymbol, topMatch.OldRoot.SyntaxTree, topMatch.NewRoot.SyntaxTree) ? symbolKey : null)); } else if (newSymbol is ITypeParameterSymbol) { var containingTypeSymbolKey = SymbolKey.Create(newSymbol.ContainingSymbol, cancellationToken); semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, containingTypeSymbolKey, syntaxMap, syntaxMapTree: null, IsPartialEdit(oldSymbol.ContainingSymbol, newSymbol.ContainingSymbol, topMatch.OldRoot.SyntaxTree, topMatch.NewRoot.SyntaxTree) ? containingTypeSymbolKey : null)); } else if (newSymbol is IFieldSymbol or IPropertySymbol or IEventSymbol) { semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, SymbolKey.Create(newSymbol, cancellationToken), syntaxMap, syntaxMapTree: null, partialType: null)); } else if (newSymbol is IParameterSymbol) { var newContainingSymbol = newSymbol.ContainingSymbol; semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, SymbolKey.Create(newContainingSymbol, cancellationToken), syntaxMap, syntaxMapTree: null, partialType: null)); // attributes applied on parameters of a delegate are applied to both Invoke and BeginInvoke methods if (newContainingSymbol.ContainingSymbol is INamedTypeSymbol { TypeKind: TypeKind.Delegate } newContainingDelegateType) { AddDelegateBeginInvokeEdit(newContainingDelegateType); } } // attribute applied on parameters or return value of a delegate are applied to both Invoke and BeginInvoke methods void AddDelegateBeginInvokeEdit(INamedTypeSymbol delegateType) { Debug.Assert(semanticEdits != null); var beginInvokeMethod = delegateType.GetMembers("BeginInvoke").FirstOrDefault(); if (beginInvokeMethod != null) { semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, SymbolKey.Create(beginInvokeMethod, cancellationToken), syntaxMap, syntaxMapTree: null, partialType: null)); } } } private void ReportCustomAttributeRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol oldSymbol, ISymbol newSymbol, SyntaxNode? newNode, Compilation newCompilation, EditAndContinueCapabilities capabilities, out bool hasAttributeChange, out bool hasReturnTypeAttributeChange, CancellationToken cancellationToken) { // This is the only case we care about whether to issue an edit or not, because this is the only case where types have their attributes checked // and types are the only things that would otherwise not have edits reported. hasAttributeChange = ReportCustomAttributeRudeEdits(diagnostics, oldSymbol.GetAttributes(), newSymbol.GetAttributes(), oldSymbol, newSymbol, newNode, newCompilation, capabilities, cancellationToken); hasReturnTypeAttributeChange = false; if (oldSymbol is IMethodSymbol oldMethod && newSymbol is IMethodSymbol newMethod) { hasReturnTypeAttributeChange |= ReportCustomAttributeRudeEdits(diagnostics, oldMethod.GetReturnTypeAttributes(), newMethod.GetReturnTypeAttributes(), oldSymbol, newSymbol, newNode, newCompilation, capabilities, cancellationToken); } else if (oldSymbol is INamedTypeSymbol { DelegateInvokeMethod: not null and var oldInvokeMethod } && newSymbol is INamedTypeSymbol { DelegateInvokeMethod: not null and var newInvokeMethod }) { hasReturnTypeAttributeChange |= ReportCustomAttributeRudeEdits(diagnostics, oldInvokeMethod.GetReturnTypeAttributes(), newInvokeMethod.GetReturnTypeAttributes(), oldSymbol, newSymbol, newNode, newCompilation, capabilities, cancellationToken); } } private bool ReportCustomAttributeRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, ImmutableArray<AttributeData>? oldAttributes, ImmutableArray<AttributeData> newAttributes, ISymbol oldSymbol, ISymbol newSymbol, SyntaxNode? newNode, Compilation newCompilation, EditAndContinueCapabilities capabilities, CancellationToken cancellationToken) { using var _ = ArrayBuilder<AttributeData>.GetInstance(out var changedAttributes); FindChangedAttributes(oldAttributes, newAttributes, changedAttributes); if (oldAttributes.HasValue) { FindChangedAttributes(newAttributes, oldAttributes.Value, changedAttributes); } if (changedAttributes.Count == 0) { return false; } // We need diagnostics reported if the runtime doesn't support changing attributes, // but even if it does, only attributes stored in the CustomAttributes table are editable if (!capabilities.HasFlag(EditAndContinueCapabilities.ChangeCustomAttributes) || changedAttributes.Any(IsNonCustomAttribute)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingAttributesNotSupportedByRuntime, oldSymbol, newSymbol, newNode, newCompilation, cancellationToken); // If the runtime doesn't support edits then pretend there weren't changes, so no edits are produced return false; } return true; static void FindChangedAttributes(ImmutableArray<AttributeData>? oldAttributes, ImmutableArray<AttributeData> newAttributes, ArrayBuilder<AttributeData> changedAttributes) { for (var i = 0; i < newAttributes.Length; i++) { var newAttribute = newAttributes[i]; var oldAttribute = FindMatch(newAttribute, oldAttributes); if (oldAttribute is null) { changedAttributes.Add(newAttribute); } } } static AttributeData? FindMatch(AttributeData attribute, ImmutableArray<AttributeData>? oldAttributes) { if (!oldAttributes.HasValue) { return null; } foreach (var match in oldAttributes.Value) { if (SymbolEquivalenceComparer.Instance.Equals(match.AttributeClass, attribute.AttributeClass)) { if (SymbolEquivalenceComparer.Instance.Equals(match.AttributeConstructor, attribute.AttributeConstructor) && match.ConstructorArguments.SequenceEqual(attribute.ConstructorArguments, TypedConstantComparer.Instance) && match.NamedArguments.SequenceEqual(attribute.NamedArguments, NamedArgumentComparer.Instance)) { return match; } } } return null; } static bool IsNonCustomAttribute(AttributeData attribute) { // TODO: Use a compiler API to get this information rather than hard coding a list: https://github.com/dotnet/roslyn/issues/53410 // This list comes from ShouldEmitAttribute in src\Compilers\CSharp\Portable\Symbols\Attributes\AttributeData.cs // and src\Compilers\VisualBasic\Portable\Symbols\Attributes\AttributeData.vb return attribute.AttributeClass?.ToNameDisplayString() switch { "System.CLSCompliantAttribute" => true, "System.Diagnostics.CodeAnalysis.AllowNullAttribute" => true, "System.Diagnostics.CodeAnalysis.DisallowNullAttribute" => true, "System.Diagnostics.CodeAnalysis.MaybeNullAttribute" => true, "System.Diagnostics.CodeAnalysis.NotNullAttribute" => true, "System.NonSerializedAttribute" => true, "System.Reflection.AssemblyAlgorithmIdAttribute" => true, "System.Reflection.AssemblyCultureAttribute" => true, "System.Reflection.AssemblyFlagsAttribute" => true, "System.Reflection.AssemblyVersionAttribute" => true, "System.Runtime.CompilerServices.DllImportAttribute" => true, // Already covered by other rude edits, but included for completeness "System.Runtime.CompilerServices.IndexerNameAttribute" => true, "System.Runtime.CompilerServices.MethodImplAttribute" => true, "System.Runtime.CompilerServices.SpecialNameAttribute" => true, "System.Runtime.CompilerServices.TypeForwardedToAttribute" => true, "System.Runtime.InteropServices.ComImportAttribute" => true, "System.Runtime.InteropServices.DefaultParameterValueAttribute" => true, "System.Runtime.InteropServices.FieldOffsetAttribute" => true, "System.Runtime.InteropServices.InAttribute" => true, "System.Runtime.InteropServices.MarshalAsAttribute" => true, "System.Runtime.InteropServices.OptionalAttribute" => true, "System.Runtime.InteropServices.OutAttribute" => true, "System.Runtime.InteropServices.PreserveSigAttribute" => true, "System.Runtime.InteropServices.StructLayoutAttribute" => true, "System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeImportAttribute" => true, "System.Security.DynamicSecurityMethodAttribute" => true, "System.SerializableAttribute" => true, not null => IsSecurityAttribute(attribute.AttributeClass), _ => false }; } static bool IsSecurityAttribute(INamedTypeSymbol namedTypeSymbol) { // Security attributes are any attribute derived from System.Security.Permissions.SecurityAttribute, directly or indirectly var symbol = namedTypeSymbol; while (symbol is not null) { if (symbol.ToNameDisplayString() == "System.Security.Permissions.SecurityAttribute") { return true; } symbol = symbol.BaseType; } return false; } } private static bool CanAddNewMember(ISymbol newSymbol, EditAndContinueCapabilities capabilities) { if (newSymbol is IMethodSymbol or IPropertySymbol) // Properties are just get_ and set_ methods { return capabilities.HasFlag(EditAndContinueCapabilities.AddMethodToExistingType); } else if (newSymbol is IFieldSymbol field) { if (field.IsStatic) { return capabilities.HasFlag(EditAndContinueCapabilities.AddStaticFieldToExistingType); } return capabilities.HasFlag(EditAndContinueCapabilities.AddInstanceFieldToExistingType); } return true; } private static void AddEditsForSynthesizedRecordMembers(Compilation compilation, INamedTypeSymbol recordType, ArrayBuilder<SemanticEditInfo> semanticEdits, CancellationToken cancellationToken) { foreach (var member in GetRecordUpdatedSynthesizedMembers(compilation, recordType)) { var symbolKey = SymbolKey.Create(member, cancellationToken); semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, symbolKey, syntaxMap: null, syntaxMapTree: null, partialType: null)); } } private static IEnumerable<ISymbol> GetRecordUpdatedSynthesizedMembers(Compilation compilation, INamedTypeSymbol record) { // All methods that are updated have well known names, and calling GetMembers(string) is // faster than enumerating. // When a new field or property is added the PrintMembers, Equals(R) and GetHashCode() methods are updated // We don't need to worry about Deconstruct because it only changes when a new positional parameter // is added, and those are rude edits (due to adding a constructor parameter). // We don't need to worry about the constructors as they are reported elsewhere. // We have to use SingleOrDefault and check IsImplicitlyDeclared because the user can provide their // own implementation of these methods, and edits to them are handled by normal processing. var result = record.GetMembers(WellKnownMemberNames.PrintMembersMethodName) .OfType<IMethodSymbol>() .SingleOrDefault(m => m.IsImplicitlyDeclared && m.Parameters.Length == 1 && SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, compilation.GetTypeByMetadataName(typeof(StringBuilder).FullName!)) && SymbolEqualityComparer.Default.Equals(m.ReturnType, compilation.GetTypeByMetadataName(typeof(bool).FullName!))); if (result is not null) { yield return result; } result = record.GetMembers(WellKnownMemberNames.ObjectEquals) .OfType<IMethodSymbol>() .SingleOrDefault(m => m.IsImplicitlyDeclared && m.Parameters.Length == 1 && SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType)); if (result is not null) { yield return result; } result = record.GetMembers(WellKnownMemberNames.ObjectGetHashCode) .OfType<IMethodSymbol>() .SingleOrDefault(m => m.IsImplicitlyDeclared && m.Parameters.Length == 0); if (result is not null) { yield return result; } } private void ReportDeletedMemberRudeEdit( ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol oldSymbol, Compilation newCompilation, RudeEditKind rudeEditKind, CancellationToken cancellationToken) { var newNode = GetDeleteRudeEditDiagnosticNode(oldSymbol, newCompilation, cancellationToken); diagnostics.Add(new RudeEditDiagnostic( rudeEditKind, GetDiagnosticSpan(newNode, EditKind.Delete), arguments: new[] { string.Format(FeaturesResources.member_kind_and_name, GetDisplayName(oldSymbol), oldSymbol.ToDisplayString(s_unqualifiedMemberDisplayFormat)) })); } private void ReportUpdateRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, RudeEditKind rudeEdit, SyntaxNode newNode) { diagnostics.Add(new RudeEditDiagnostic( rudeEdit, GetDiagnosticSpan(newNode, EditKind.Update), newNode, new[] { GetDisplayName(newNode) })); } private void ReportUpdateRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, RudeEditKind rudeEdit, ISymbol newSymbol, SyntaxNode? newNode, CancellationToken cancellationToken) { var node = newNode ?? GetRudeEditDiagnosticNode(newSymbol, cancellationToken); var span = (rudeEdit == RudeEditKind.ChangeImplicitMainReturnType) ? GetGlobalStatementDiagnosticSpan(node) : GetDiagnosticSpan(node, EditKind.Update); var arguments = rudeEdit switch { RudeEditKind.TypeKindUpdate or RudeEditKind.ChangeImplicitMainReturnType or RudeEditKind.GenericMethodUpdate or RudeEditKind.GenericTypeUpdate => Array.Empty<string>(), RudeEditKind.ChangingReloadableTypeNotSupportedByRuntime => new[] { CreateNewOnMetadataUpdateAttributeName }, _ => new[] { GetDisplayName(newSymbol) } }; diagnostics.Add(new RudeEditDiagnostic(rudeEdit, span, node, arguments)); } private void ReportUpdateRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, RudeEditKind rudeEdit, ISymbol oldSymbol, ISymbol newSymbol, SyntaxNode? newNode, Compilation newCompilation, CancellationToken cancellationToken) { if (newSymbol.IsImplicitlyDeclared) { ReportDeletedMemberRudeEdit(diagnostics, oldSymbol, newCompilation, rudeEdit, cancellationToken); } else { ReportUpdateRudeEdit(diagnostics, rudeEdit, newSymbol, newNode, cancellationToken); } } private static SyntaxNode GetRudeEditDiagnosticNode(ISymbol symbol, CancellationToken cancellationToken) { var container = symbol; while (container != null) { if (container.DeclaringSyntaxReferences.Length > 0) { return container.DeclaringSyntaxReferences[0].GetSyntax(cancellationToken); } container = container.ContainingSymbol; } throw ExceptionUtilities.Unreachable; } private static SyntaxNode GetDeleteRudeEditDiagnosticNode(ISymbol oldSymbol, Compilation newCompilation, CancellationToken cancellationToken) { var oldContainer = oldSymbol.ContainingSymbol; while (oldContainer != null) { var containerKey = SymbolKey.Create(oldContainer, cancellationToken); var newContainer = containerKey.Resolve(newCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; if (newContainer != null) { return GetRudeEditDiagnosticNode(newContainer, cancellationToken); } oldContainer = oldContainer.ContainingSymbol; } throw ExceptionUtilities.Unreachable; } #region Type Layout Update Validation internal void ReportTypeLayoutUpdateRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol newSymbol, SyntaxNode newSyntax, SemanticModel newModel, ref INamedTypeSymbol? lazyLayoutAttribute) { switch (newSymbol.Kind) { case SymbolKind.Field: if (HasExplicitOrSequentialLayout(newSymbol.ContainingType, newModel, ref lazyLayoutAttribute)) { ReportTypeLayoutUpdateRudeEdits(diagnostics, newSymbol, newSyntax); } break; case SymbolKind.Property: if (HasBackingField(newSyntax) && HasExplicitOrSequentialLayout(newSymbol.ContainingType, newModel, ref lazyLayoutAttribute)) { ReportTypeLayoutUpdateRudeEdits(diagnostics, newSymbol, newSyntax); } break; case SymbolKind.Event: if (HasBackingField((IEventSymbol)newSymbol) && HasExplicitOrSequentialLayout(newSymbol.ContainingType, newModel, ref lazyLayoutAttribute)) { ReportTypeLayoutUpdateRudeEdits(diagnostics, newSymbol, newSyntax); } break; } } private void ReportTypeLayoutUpdateRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol symbol, SyntaxNode syntax) { var intoStruct = symbol.ContainingType.TypeKind == TypeKind.Struct; diagnostics.Add(new RudeEditDiagnostic( intoStruct ? RudeEditKind.InsertIntoStruct : RudeEditKind.InsertIntoClassWithLayout, syntax.Span, syntax, new[] { GetDisplayName(syntax, EditKind.Insert), GetDisplayName(TryGetContainingTypeDeclaration(syntax)!, EditKind.Update) })); } private static bool HasBackingField(IEventSymbol @event) { #nullable disable // https://github.com/dotnet/roslyn/issues/39288 return @event.AddMethod.IsImplicitlyDeclared #nullable enable && [email protected]; } private static bool HasExplicitOrSequentialLayout( INamedTypeSymbol type, SemanticModel model, ref INamedTypeSymbol? lazyLayoutAttribute) { if (type.TypeKind == TypeKind.Struct) { return true; } if (type.TypeKind != TypeKind.Class) { return false; } // Fields can't be inserted into a class with explicit or sequential layout var attributes = type.GetAttributes(); if (attributes.Length == 0) { return false; } lazyLayoutAttribute ??= model.Compilation.GetTypeByMetadataName(typeof(StructLayoutAttribute).FullName!); if (lazyLayoutAttribute == null) { return false; } foreach (var attribute in attributes) { RoslynDebug.Assert(attribute.AttributeClass is object); if (attribute.AttributeClass.Equals(lazyLayoutAttribute) && attribute.ConstructorArguments.Length == 1) { var layoutValue = attribute.ConstructorArguments.Single().Value; return (layoutValue is int ? (int)layoutValue : layoutValue is short ? (short)layoutValue : (int)LayoutKind.Auto) != (int)LayoutKind.Auto; } } return false; } #endregion private Func<SyntaxNode, SyntaxNode?> CreateSyntaxMapForEquivalentNodes(SyntaxNode oldDeclaration, SyntaxNode newDeclaration) { return newNode => newDeclaration.FullSpan.Contains(newNode.SpanStart) ? FindDeclarationBodyPartner(newDeclaration, oldDeclaration, newNode) : null; } private static Func<SyntaxNode, SyntaxNode?> CreateSyntaxMap(IReadOnlyDictionary<SyntaxNode, SyntaxNode> reverseMap) => newNode => reverseMap.TryGetValue(newNode, out var oldNode) ? oldNode : null; private Func<SyntaxNode, SyntaxNode?>? CreateAggregateSyntaxMap( IReadOnlyDictionary<SyntaxNode, SyntaxNode> reverseTopMatches, IReadOnlyDictionary<SyntaxNode, Func<SyntaxNode, SyntaxNode?>?> changedDeclarations) { return newNode => { // containing declaration if (!TryFindMemberDeclaration(root: null, newNode, out var newDeclarations)) { return null; } foreach (var newDeclaration in newDeclarations) { // The node is in a field, property or constructor declaration that has been changed: if (changedDeclarations.TryGetValue(newDeclaration, out var syntaxMap)) { // If syntax map is not available the declaration was either // 1) updated but is not active // 2) inserted return syntaxMap?.Invoke(newNode); } // The node is in a declaration that hasn't been changed: if (reverseTopMatches.TryGetValue(newDeclaration, out var oldDeclaration)) { return FindDeclarationBodyPartner(newDeclaration, oldDeclaration, newNode); } } return null; }; } #region Constructors and Initializers /// <summary> /// Called when a body of a constructor or an initializer of a member is updated or inserted. /// </summary> private static void DeferConstructorEdit( INamedTypeSymbol oldType, INamedTypeSymbol newType, SyntaxNode? newDeclaration, Func<SyntaxNode, SyntaxNode?>? syntaxMap, bool isStatic, ref PooledDictionary<INamedTypeSymbol, ConstructorEdit>? instanceConstructorEdits, ref PooledDictionary<INamedTypeSymbol, ConstructorEdit>? staticConstructorEdits) { Dictionary<INamedTypeSymbol, ConstructorEdit> constructorEdits; if (isStatic) { constructorEdits = staticConstructorEdits ??= PooledDictionary<INamedTypeSymbol, ConstructorEdit>.GetInstance(); } else { constructorEdits = instanceConstructorEdits ??= PooledDictionary<INamedTypeSymbol, ConstructorEdit>.GetInstance(); } if (!constructorEdits.TryGetValue(newType, out var constructorEdit)) { constructorEdits.Add(newType, constructorEdit = new ConstructorEdit(oldType)); } if (newDeclaration != null && !constructorEdit.ChangedDeclarations.ContainsKey(newDeclaration)) { constructorEdit.ChangedDeclarations.Add(newDeclaration, syntaxMap); } } private void AddConstructorEdits( IReadOnlyDictionary<INamedTypeSymbol, ConstructorEdit> updatedTypes, Match<SyntaxNode> topMatch, SemanticModel? oldModel, Compilation oldCompilation, Compilation newCompilation, IReadOnlySet<ISymbol> processedSymbols, EditAndContinueCapabilities capabilities, bool isStatic, [Out] ArrayBuilder<SemanticEditInfo> semanticEdits, [Out] ArrayBuilder<RudeEditDiagnostic> diagnostics, CancellationToken cancellationToken) { var oldSyntaxTree = topMatch.OldRoot.SyntaxTree; var newSyntaxTree = topMatch.NewRoot.SyntaxTree; foreach (var (newType, updatesInCurrentDocument) in updatedTypes) { var oldType = updatesInCurrentDocument.OldType; var anyInitializerUpdatesInCurrentDocument = updatesInCurrentDocument.ChangedDeclarations.Keys.Any(IsDeclarationWithInitializer); var isPartialEdit = IsPartialEdit(oldType, newType, oldSyntaxTree, newSyntaxTree); // Create a syntax map that aggregates syntax maps of the constructor body and all initializers in this document. // Use syntax maps stored in update.ChangedDeclarations and fallback to 1:1 map for unchanged members. // // This aggregated map will be combined with similar maps capturing members declared in partial type declarations // located in other documents when the semantic edits are merged across all changed documents of the project. // // We will create an aggregate syntax map even in cases when we don't necessarily need it, // for example if none of the edited declarations are active. It's ok to have a map that we don't need. // This is simpler than detecting whether or not some of the initializers/constructors contain active statements. var aggregateSyntaxMap = CreateAggregateSyntaxMap(topMatch.ReverseMatches, updatesInCurrentDocument.ChangedDeclarations); bool? lazyOldTypeHasMemberInitializerContainingLambda = null; foreach (var newCtor in isStatic ? newType.StaticConstructors : newType.InstanceConstructors) { if (processedSymbols.Contains(newCtor)) { // we already have an edit for the new constructor continue; } var newCtorKey = SymbolKey.Create(newCtor, cancellationToken); var syntaxMapToUse = aggregateSyntaxMap; SyntaxNode? newDeclaration = null; ISymbol? oldCtor; if (!newCtor.IsImplicitlyDeclared) { // Constructors have to have a single declaration syntax, they can't be partial newDeclaration = GetSymbolDeclarationSyntax(newCtor.DeclaringSyntaxReferences.Single(), cancellationToken); // Implicit record constructors are represented by the record declaration itself. // https://github.com/dotnet/roslyn/issues/54403 var isPrimaryRecordConstructor = IsRecordDeclaration(newDeclaration); // Constructor that doesn't contain initializers had a corresponding semantic edit produced previously // or was not edited. In either case we should not produce a semantic edit for it. if (!isPrimaryRecordConstructor && !IsConstructorWithMemberInitializers(newDeclaration)) { continue; } // If no initializer updates were made in the type we only need to produce semantic edits for constructors // whose body has been updated, otherwise we need to produce edits for all constructors that include initializers. // If changes were made to initializers or constructors of a partial type in another document they will be merged // when aggregating semantic edits from all changed documents. Rude edits resulting from those changes, if any, will // be reported in the document they were made in. if (!isPrimaryRecordConstructor && !anyInitializerUpdatesInCurrentDocument && !updatesInCurrentDocument.ChangedDeclarations.ContainsKey(newDeclaration)) { continue; } // To avoid costly SymbolKey resolution we first try to match the constructor in the current document // and special case parameter-less constructor. // In the case of records, newDeclaration will point to the record declaration, take the slow path. if (!isPrimaryRecordConstructor && topMatch.TryGetOldNode(newDeclaration, out var oldDeclaration)) { Contract.ThrowIfNull(oldModel); oldCtor = oldModel.GetDeclaredSymbol(oldDeclaration, cancellationToken); Contract.ThrowIfFalse(oldCtor is IMethodSymbol { MethodKind: MethodKind.Constructor or MethodKind.StaticConstructor }); } else if (!isPrimaryRecordConstructor && newCtor.Parameters.Length == 0) { oldCtor = TryGetParameterlessConstructor(oldType, isStatic); } else { var resolution = newCtorKey.Resolve(oldCompilation, ignoreAssemblyKey: true, cancellationToken); // There may be semantic errors in the compilation that result in multiple candidates. // Pick the first candidate. oldCtor = resolution.Symbol; } if (oldCtor == null && HasMemberInitializerContainingLambda(oldType, isStatic, ref lazyOldTypeHasMemberInitializerContainingLambda, cancellationToken)) { // TODO (bug https://github.com/dotnet/roslyn/issues/2504) // rude edit: Adding a constructor to a type with a field or property initializer that contains an anonymous function diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, GetDiagnosticSpan(newDeclaration, EditKind.Insert))); continue; } // Report an error if the updated constructor's declaration is in the current document // and its body edit is disallowed (e.g. contains stackalloc). if (oldCtor != null && newDeclaration.SyntaxTree == newSyntaxTree && anyInitializerUpdatesInCurrentDocument) { // attribute rude edit to one of the modified members var firstSpan = updatesInCurrentDocument.ChangedDeclarations.Keys.Where(IsDeclarationWithInitializer).Aggregate( (min: int.MaxValue, span: default(TextSpan)), (accumulate, node) => (node.SpanStart < accumulate.min) ? (node.SpanStart, node.Span) : accumulate).span; Contract.ThrowIfTrue(firstSpan.IsEmpty); ReportMemberBodyUpdateRudeEdits(diagnostics, newDeclaration, firstSpan); } // When explicitly implementing the copy constructor of a record the parameter name must match for symbol matching to work // TODO: Remove this requirement with https://github.com/dotnet/roslyn/issues/52563 if (oldCtor != null && !isPrimaryRecordConstructor && oldCtor.DeclaringSyntaxReferences.Length == 0 && newCtor.Parameters.Length == 1 && newType.IsRecord && oldCtor.GetParameters().First().Name != newCtor.GetParameters().First().Name) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ExplicitRecordMethodParameterNamesMustMatch, GetDiagnosticSpan(newDeclaration, EditKind.Update), arguments: new[] { oldCtor.ToDisplayString(SymbolDisplayFormats.NameFormat) })); continue; } } else { if (newCtor.Parameters.Length == 1) { // New constructor is implicitly declared with a parameter, so its the copy constructor of a record Debug.Assert(oldType.IsRecord); Debug.Assert(newType.IsRecord); // We only need an edit for this if the number of properties or fields on the record has changed. Changes to // initializers, or whether the property is part of the primary constructor, will still come through this code // path because they need an edit to the other constructor, but not the copy construcor. if (oldType.GetMembers().OfType<IPropertySymbol>().Count() == newType.GetMembers().OfType<IPropertySymbol>().Count() && oldType.GetMembers().OfType<IFieldSymbol>().Count() == newType.GetMembers().OfType<IFieldSymbol>().Count()) { continue; } oldCtor = oldType.InstanceConstructors.Single(c => c.Parameters.Length == 1 && SymbolEqualityComparer.Default.Equals(c.Parameters[0].Type, c.ContainingType)); // The copy constructor does not have a syntax map syntaxMapToUse = null; // Since there is no syntax map, we don't need to handle anything special to merge them for partial types. // The easiest way to do this is just to pretend this isn't a partial edit. isPartialEdit = false; } else { // New constructor is implicitly declared so it must be parameterless. // // Instance constructor: // Its presence indicates there are no other instance constructors in the new type and therefore // there must be a single parameterless instance constructor in the old type (constructors with parameters can't be removed). // // Static constructor: // Static constructor is always parameterless and not implicitly generated if there are no static initializers. oldCtor = TryGetParameterlessConstructor(oldType, isStatic); } Contract.ThrowIfFalse(isStatic || oldCtor != null); } if (oldCtor != null) { AnalyzeSymbolUpdate(oldCtor, newCtor, newDeclaration, newCompilation, topMatch, capabilities, diagnostics, semanticEdits, syntaxMapToUse, cancellationToken); semanticEdits.Add(new SemanticEditInfo( SemanticEditKind.Update, newCtorKey, syntaxMapToUse, syntaxMapTree: isPartialEdit ? newSyntaxTree : null, partialType: isPartialEdit ? SymbolKey.Create(newType, cancellationToken) : null)); } else { semanticEdits.Add(new SemanticEditInfo( SemanticEditKind.Insert, newCtorKey, syntaxMap: null, syntaxMapTree: null, partialType: null)); } } } } private bool HasMemberInitializerContainingLambda(INamedTypeSymbol type, bool isStatic, ref bool? lazyHasMemberInitializerContainingLambda, CancellationToken cancellationToken) { if (lazyHasMemberInitializerContainingLambda == null) { // checking the old type for existing lambdas (it's ok for the new initializers to contain lambdas) lazyHasMemberInitializerContainingLambda = HasMemberInitializerContainingLambda(type, isStatic, cancellationToken); } return lazyHasMemberInitializerContainingLambda.Value; } private bool HasMemberInitializerContainingLambda(INamedTypeSymbol type, bool isStatic, CancellationToken cancellationToken) { // checking the old type for existing lambdas (it's ok for the new initializers to contain lambdas) foreach (var member in type.GetMembers()) { if (member.IsStatic == isStatic && (member.Kind == SymbolKind.Field || member.Kind == SymbolKind.Property) && member.DeclaringSyntaxReferences.Length > 0) // skip generated fields (e.g. VB auto-property backing fields) { var syntax = GetSymbolDeclarationSyntax(member.DeclaringSyntaxReferences.Single(), cancellationToken); if (IsDeclarationWithInitializer(syntax) && ContainsLambda(syntax)) { return true; } } } return false; } private static ISymbol? TryGetParameterlessConstructor(INamedTypeSymbol type, bool isStatic) { var oldCtors = isStatic ? type.StaticConstructors : type.InstanceConstructors; if (isStatic) { return type.StaticConstructors.FirstOrDefault(); } else { return type.InstanceConstructors.FirstOrDefault(m => m.Parameters.Length == 0); } } private static bool IsPartialEdit(ISymbol? oldSymbol, ISymbol? newSymbol, SyntaxTree oldSyntaxTree, SyntaxTree newSyntaxTree) { // If any of the partial declarations of the new or the old type are in another document // the edit will need to be merged with other partial edits with matching partial type static bool IsNotInDocument(SyntaxReference reference, SyntaxTree syntaxTree) => reference.SyntaxTree != syntaxTree; return oldSymbol?.Kind == SymbolKind.NamedType && oldSymbol.DeclaringSyntaxReferences.Length > 1 && oldSymbol.DeclaringSyntaxReferences.Any(IsNotInDocument, oldSyntaxTree) || newSymbol?.Kind == SymbolKind.NamedType && newSymbol.DeclaringSyntaxReferences.Length > 1 && newSymbol.DeclaringSyntaxReferences.Any(IsNotInDocument, newSyntaxTree); } #endregion #region Lambdas and Closures private void ReportLambdaAndClosureRudeEdits( SemanticModel oldModel, SyntaxNode oldMemberBody, SemanticModel newModel, SyntaxNode newMemberBody, ISymbol newMember, IReadOnlyDictionary<SyntaxNode, LambdaInfo>? matchedLambdas, BidirectionalMap<SyntaxNode> map, EditAndContinueCapabilities capabilities, ArrayBuilder<RudeEditDiagnostic> diagnostics, out bool syntaxMapRequired, CancellationToken cancellationToken) { syntaxMapRequired = false; if (matchedLambdas != null) { var anySignatureErrors = false; foreach (var (oldLambdaBody, newLambdaInfo) in matchedLambdas) { // Any unmatched lambdas would have contained an active statement and a rude edit would be reported in syntax analysis phase. // Skip the rest of lambda and closure analysis if such lambdas are present. if (newLambdaInfo.Match == null || newLambdaInfo.NewBody == null) { return; } ReportLambdaSignatureRudeEdits(diagnostics, oldModel, oldLambdaBody, newModel, newLambdaInfo.NewBody, capabilities, out var hasErrors, cancellationToken); anySignatureErrors |= hasErrors; } ArrayBuilder<SyntaxNode>? lazyNewErroneousClauses = null; foreach (var (oldQueryClause, newQueryClause) in map.Forward) { if (!QueryClauseLambdasTypeEquivalent(oldModel, oldQueryClause, newModel, newQueryClause, cancellationToken)) { lazyNewErroneousClauses ??= ArrayBuilder<SyntaxNode>.GetInstance(); lazyNewErroneousClauses.Add(newQueryClause); } } if (lazyNewErroneousClauses != null) { foreach (var newQueryClause in from clause in lazyNewErroneousClauses orderby clause.SpanStart group clause by GetContainingQueryExpression(clause) into clausesByQuery select clausesByQuery.First()) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingQueryLambdaType, GetDiagnosticSpan(newQueryClause, EditKind.Update), newQueryClause, new[] { GetDisplayName(newQueryClause, EditKind.Update) })); } lazyNewErroneousClauses.Free(); anySignatureErrors = true; } // only dig into captures if lambda signatures match if (anySignatureErrors) { return; } } using var oldLambdaBodyEnumerator = GetLambdaBodies(oldMemberBody).GetEnumerator(); using var newLambdaBodyEnumerator = GetLambdaBodies(newMemberBody).GetEnumerator(); var oldHasLambdas = oldLambdaBodyEnumerator.MoveNext(); var newHasLambdas = newLambdaBodyEnumerator.MoveNext(); // Exit early if there are no lambdas in the method to avoid expensive data flow analysis: if (!oldHasLambdas && !newHasLambdas) { return; } var oldCaptures = GetCapturedVariables(oldModel, oldMemberBody); var newCaptures = GetCapturedVariables(newModel, newMemberBody); // { new capture index -> old capture index } using var _1 = ArrayBuilder<int>.GetInstance(newCaptures.Length, fillWithValue: 0, out var reverseCapturesMap); // { new capture index -> new closure scope or null for "this" } using var _2 = ArrayBuilder<SyntaxNode?>.GetInstance(newCaptures.Length, fillWithValue: null, out var newCapturesToClosureScopes); // Can be calculated from other maps but it's simpler to just calculate it upfront. // { old capture index -> old closure scope or null for "this" } using var _3 = ArrayBuilder<SyntaxNode?>.GetInstance(oldCaptures.Length, fillWithValue: null, out var oldCapturesToClosureScopes); CalculateCapturedVariablesMaps( oldCaptures, oldMemberBody, newCaptures, newMember, newMemberBody, map, reverseCapturesMap, newCapturesToClosureScopes, oldCapturesToClosureScopes, diagnostics, out var anyCaptureErrors, cancellationToken); if (anyCaptureErrors) { return; } // Every captured variable accessed in the new lambda has to be // accessed in the old lambda as well and vice versa. // // An added lambda can only reference captured variables that // // This requirement ensures that: // - Lambda methods are generated to the same frame as before, so they can be updated in-place. // - "Parent" links between closure scopes are preserved. using var _11 = PooledDictionary<ISymbol, int>.GetInstance(out var oldCapturesIndex); using var _12 = PooledDictionary<ISymbol, int>.GetInstance(out var newCapturesIndex); BuildIndex(oldCapturesIndex, oldCaptures); BuildIndex(newCapturesIndex, newCaptures); if (matchedLambdas != null) { var mappedLambdasHaveErrors = false; foreach (var (oldLambdaBody, newLambdaInfo) in matchedLambdas) { var newLambdaBody = newLambdaInfo.NewBody; // The map now contains only matched lambdas. Any unmatched ones would have contained an active statement and // a rude edit would be reported in syntax analysis phase. RoslynDebug.Assert(newLambdaInfo.Match != null && newLambdaBody != null); var accessedOldCaptures = GetAccessedCaptures(oldLambdaBody, oldModel, oldCaptures, oldCapturesIndex); var accessedNewCaptures = GetAccessedCaptures(newLambdaBody, newModel, newCaptures, newCapturesIndex); // Requirement: // (new(ReadInside) \/ new(WrittenInside)) /\ new(Captured) == (old(ReadInside) \/ old(WrittenInside)) /\ old(Captured) for (var newCaptureIndex = 0; newCaptureIndex < newCaptures.Length; newCaptureIndex++) { var newAccessed = accessedNewCaptures[newCaptureIndex]; var oldAccessed = accessedOldCaptures[reverseCapturesMap[newCaptureIndex]]; if (newAccessed != oldAccessed) { var newCapture = newCaptures[newCaptureIndex]; var rudeEdit = newAccessed ? RudeEditKind.AccessingCapturedVariableInLambda : RudeEditKind.NotAccessingCapturedVariableInLambda; var arguments = new[] { newCapture.Name, GetDisplayName(GetLambda(newLambdaBody)) }; if (newCapture.IsThisParameter() || oldAccessed) { // changed accessed to "this", or captured variable accessed in old lambda is not accessed in the new lambda diagnostics.Add(new RudeEditDiagnostic(rudeEdit, GetDiagnosticSpan(GetLambda(newLambdaBody), EditKind.Update), null, arguments)); } else if (newAccessed) { // captured variable accessed in new lambda is not accessed in the old lambda var hasUseSites = false; foreach (var useSite in GetVariableUseSites(GetLambdaBodyExpressionsAndStatements(newLambdaBody), newCapture, newModel, cancellationToken)) { hasUseSites = true; diagnostics.Add(new RudeEditDiagnostic(rudeEdit, useSite.Span, null, arguments)); } Debug.Assert(hasUseSites); } mappedLambdasHaveErrors = true; } } } if (mappedLambdasHaveErrors) { return; } } // Report rude edits for lambdas added to the method. // We already checked that no new captures are introduced or removed. // We also need to make sure that no new parent frame links are introduced. // // We could implement the same analysis as the compiler does when rewriting lambdas - // to determine what closure scopes are connected at runtime via parent link, // and then disallow adding a lambda that connects two previously unconnected // groups of scopes. // // However even if we implemented that logic here, it would be challenging to // present the result of the analysis to the user in a short comprehensible error message. // // In practice, we believe the common scenarios are (in order of commonality): // 1) adding a static lambda // 2) adding a lambda that accesses only "this" // 3) adding a lambda that accesses variables from the same scope // 4) adding a lambda that accesses "this" and variables from a single scope // 5) adding a lambda that accesses variables from different scopes that are linked // 6) adding a lambda that accesses variables from unlinked scopes // // We currently allow #1, #2, and #3 and report a rude edit for the other cases. // In future we might be able to enable more. var containingTypeDeclaration = TryGetContainingTypeDeclaration(newMemberBody); var isInInterfaceDeclaration = containingTypeDeclaration != null && IsInterfaceDeclaration(containingTypeDeclaration); var newHasLambdaBodies = newHasLambdas; while (newHasLambdaBodies) { var (newLambda, newLambdaBody1, newLambdaBody2) = newLambdaBodyEnumerator.Current; if (!map.Reverse.ContainsKey(newLambda)) { if (!CanAddNewLambda(newLambda, capabilities, matchedLambdas)) { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.InsertNotSupportedByRuntime, GetDiagnosticSpan(newLambda, EditKind.Insert), newLambda, new string[] { GetDisplayName(newLambda, EditKind.Insert) })); } // TODO: https://github.com/dotnet/roslyn/issues/37128 // Local functions are emitted directly to the type containing the containing method. // Although local functions are non-virtual the Core CLR currently does not support adding any method to an interface. if (isInInterfaceDeclaration && IsLocalFunction(newLambda)) { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.InsertLocalFunctionIntoInterfaceMethod, GetDiagnosticSpan(newLambda, EditKind.Insert), newLambda)); } ReportMultiScopeCaptures(newLambdaBody1, newModel, newCaptures, newCaptures, newCapturesToClosureScopes, newCapturesIndex, reverseCapturesMap, diagnostics, isInsert: true, cancellationToken: cancellationToken); if (newLambdaBody2 != null) { ReportMultiScopeCaptures(newLambdaBody2, newModel, newCaptures, newCaptures, newCapturesToClosureScopes, newCapturesIndex, reverseCapturesMap, diagnostics, isInsert: true, cancellationToken: cancellationToken); } } newHasLambdaBodies = newLambdaBodyEnumerator.MoveNext(); } // Similarly for addition. We don't allow removal of lambda that has captures from multiple scopes. var oldHasMoreLambdas = oldHasLambdas; while (oldHasMoreLambdas) { var (oldLambda, oldLambdaBody1, oldLambdaBody2) = oldLambdaBodyEnumerator.Current; if (!map.Forward.ContainsKey(oldLambda)) { ReportMultiScopeCaptures(oldLambdaBody1, oldModel, oldCaptures, newCaptures, oldCapturesToClosureScopes, oldCapturesIndex, reverseCapturesMap, diagnostics, isInsert: false, cancellationToken: cancellationToken); if (oldLambdaBody2 != null) { ReportMultiScopeCaptures(oldLambdaBody2, oldModel, oldCaptures, newCaptures, oldCapturesToClosureScopes, oldCapturesIndex, reverseCapturesMap, diagnostics, isInsert: false, cancellationToken: cancellationToken); } } oldHasMoreLambdas = oldLambdaBodyEnumerator.MoveNext(); } syntaxMapRequired = newHasLambdas; } private IEnumerable<(SyntaxNode lambda, SyntaxNode lambdaBody1, SyntaxNode? lambdaBody2)> GetLambdaBodies(SyntaxNode body) { foreach (var node in body.DescendantNodesAndSelf()) { if (TryGetLambdaBodies(node, out var body1, out var body2)) { yield return (node, body1, body2); } } } private bool CanAddNewLambda(SyntaxNode newLambda, EditAndContinueCapabilities capabilities, IReadOnlyDictionary<SyntaxNode, LambdaInfo>? matchedLambdas) { // New local functions mean new methods in existing classes if (IsLocalFunction(newLambda)) { return capabilities.HasFlag(EditAndContinueCapabilities.AddMethodToExistingType); } // New lambdas sometimes mean creating new helper classes, and sometimes mean new methods in exising helper classes // Unfortunately we are limited here in what we can do here. See: https://github.com/dotnet/roslyn/issues/52759 // If there is already a lambda in the method then the new lambda would result in a new method in the existing helper class. // This check is redundant with the below, once the limitation in the referenced issue is resolved if (matchedLambdas is { Count: > 0 }) { return capabilities.HasFlag(EditAndContinueCapabilities.AddMethodToExistingType); } // If there is already a lambda in the class then the new lambda would result in a new method in the existing helper class. // If there isn't already a lambda in the class then the new lambda would result in a new helper class. // Unfortunately right now we can't determine which of these is true so we have to just check both capabilities instead. return capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition) && capabilities.HasFlag(EditAndContinueCapabilities.AddMethodToExistingType); } private void ReportMultiScopeCaptures( SyntaxNode lambdaBody, SemanticModel model, ImmutableArray<ISymbol> captures, ImmutableArray<ISymbol> newCaptures, ArrayBuilder<SyntaxNode?> newCapturesToClosureScopes, PooledDictionary<ISymbol, int> capturesIndex, ArrayBuilder<int> reverseCapturesMap, ArrayBuilder<RudeEditDiagnostic> diagnostics, bool isInsert, CancellationToken cancellationToken) { if (captures.Length == 0) { return; } var accessedCaptures = GetAccessedCaptures(lambdaBody, model, captures, capturesIndex); var firstAccessedCaptureIndex = -1; for (var i = 0; i < captures.Length; i++) { if (accessedCaptures[i]) { if (firstAccessedCaptureIndex == -1) { firstAccessedCaptureIndex = i; } else if (newCapturesToClosureScopes[firstAccessedCaptureIndex] != newCapturesToClosureScopes[i]) { // the lambda accesses variables from two different scopes: TextSpan errorSpan; RudeEditKind rudeEdit; if (isInsert) { if (captures[i].IsThisParameter()) { errorSpan = GetDiagnosticSpan(GetLambda(lambdaBody), EditKind.Insert); } else { errorSpan = GetVariableUseSites(GetLambdaBodyExpressionsAndStatements(lambdaBody), captures[i], model, cancellationToken).First().Span; } rudeEdit = RudeEditKind.InsertLambdaWithMultiScopeCapture; } else { errorSpan = newCaptures[reverseCapturesMap.IndexOf(i)].Locations.Single().SourceSpan; rudeEdit = RudeEditKind.DeleteLambdaWithMultiScopeCapture; } diagnostics.Add(new RudeEditDiagnostic( rudeEdit, errorSpan, null, new[] { GetDisplayName(GetLambda(lambdaBody)), captures[firstAccessedCaptureIndex].Name, captures[i].Name })); break; } } } } private BitVector GetAccessedCaptures(SyntaxNode lambdaBody, SemanticModel model, ImmutableArray<ISymbol> captures, PooledDictionary<ISymbol, int> capturesIndex) { var result = BitVector.Create(captures.Length); foreach (var expressionOrStatement in GetLambdaBodyExpressionsAndStatements(lambdaBody)) { var dataFlow = model.AnalyzeDataFlow(expressionOrStatement); MarkVariables(ref result, dataFlow.ReadInside, capturesIndex); MarkVariables(ref result, dataFlow.WrittenInside, capturesIndex); } return result; } private static void MarkVariables(ref BitVector mask, ImmutableArray<ISymbol> variables, Dictionary<ISymbol, int> index) { foreach (var variable in variables) { if (index.TryGetValue(variable, out var newCaptureIndex)) { mask[newCaptureIndex] = true; } } } private static void BuildIndex<TKey>(Dictionary<TKey, int> index, ImmutableArray<TKey> array) where TKey : notnull { for (var i = 0; i < array.Length; i++) { index.Add(array[i], i); } } /// <summary> /// Returns node that represents a declaration of the symbol whose <paramref name="reference"/> is passed in. /// </summary> protected abstract SyntaxNode GetSymbolDeclarationSyntax(SyntaxReference reference, CancellationToken cancellationToken); private static TextSpan GetThisParameterDiagnosticSpan(ISymbol member) => member.Locations.First().SourceSpan; private static TextSpan GetVariableDiagnosticSpan(ISymbol local) { // Note that in VB implicit value parameter in property setter doesn't have a location. // In C# its location is the location of the setter. // See https://github.com/dotnet/roslyn/issues/14273 return local.Locations.FirstOrDefault()?.SourceSpan ?? local.ContainingSymbol.Locations.First().SourceSpan; } private static (SyntaxNode? Node, int Ordinal) GetParameterKey(IParameterSymbol parameter, CancellationToken cancellationToken) { var containingLambda = parameter.ContainingSymbol as IMethodSymbol; if (containingLambda?.MethodKind is MethodKind.LambdaMethod or MethodKind.LocalFunction) { var oldContainingLambdaSyntax = containingLambda.DeclaringSyntaxReferences.Single().GetSyntax(cancellationToken); return (oldContainingLambdaSyntax, parameter.Ordinal); } else { return (Node: null, parameter.Ordinal); } } private static bool TryMapParameter((SyntaxNode? Node, int Ordinal) parameterKey, IReadOnlyDictionary<SyntaxNode, SyntaxNode> map, out (SyntaxNode? Node, int Ordinal) mappedParameterKey) { var containingLambdaSyntax = parameterKey.Node; if (containingLambdaSyntax == null) { // method parameter: no syntax, same ordinal (can't change since method signatures must match) mappedParameterKey = parameterKey; return true; } if (map.TryGetValue(containingLambdaSyntax, out var mappedContainingLambdaSyntax)) { // parameter of an existing lambda: same ordinal (can't change since lambda signatures must match), mappedParameterKey = (mappedContainingLambdaSyntax, parameterKey.Ordinal); return true; } // no mapping mappedParameterKey = default; return false; } private void CalculateCapturedVariablesMaps( ImmutableArray<ISymbol> oldCaptures, SyntaxNode oldMemberBody, ImmutableArray<ISymbol> newCaptures, ISymbol newMember, SyntaxNode newMemberBody, BidirectionalMap<SyntaxNode> map, [Out] ArrayBuilder<int> reverseCapturesMap, // {new capture index -> old capture index} [Out] ArrayBuilder<SyntaxNode?> newCapturesToClosureScopes, // {new capture index -> new closure scope} [Out] ArrayBuilder<SyntaxNode?> oldCapturesToClosureScopes, // {old capture index -> old closure scope} [Out] ArrayBuilder<RudeEditDiagnostic> diagnostics, out bool hasErrors, CancellationToken cancellationToken) { hasErrors = false; // Validate that all variables that are/were captured in the new/old body were captured in // the old/new one and their type and scope haven't changed. // // Frames are created based upon captured variables and their scopes. If the scopes haven't changed the frames won't either. // // In future we can relax some of these limitations. // - If a newly captured variable's scope is already a closure then it is ok to lift this variable to the existing closure, // unless any lambda (or the containing member) that can access the variable is active. If it was active we would need // to copy the value of the local variable to the lifted field. // // Consider the following edit: // Gen0 Gen1 // ... ... // { { // int x = 1, y = 2; int x = 1, y = 2; // F(() => x); F(() => x); // AS-->W(y) AS-->W(y) // F(() => y); // } } // ... ... // // - If an "uncaptured" variable's scope still defines other captured variables it is ok to cease capturing the variable, // unless any lambda (or the containing member) that can access the variable is active. If it was active we would need // to copy the value of the lifted field to the local variable (consider reverse edit in the example above). // // - While building the closure tree for the new version the compiler can recreate // the closure tree of the previous version and then map // closure scopes in the new version to the previous ones, keeping empty closures around. using var _1 = PooledDictionary<SyntaxNode, int>.GetInstance(out var oldLocalCapturesBySyntax); using var _2 = PooledDictionary<(SyntaxNode? Node, int Ordinal), int>.GetInstance(out var oldParameterCapturesByLambdaAndOrdinal); for (var i = 0; i < oldCaptures.Length; i++) { var oldCapture = oldCaptures[i]; if (oldCapture.Kind == SymbolKind.Parameter) { oldParameterCapturesByLambdaAndOrdinal.Add(GetParameterKey((IParameterSymbol)oldCapture, cancellationToken), i); } else { oldLocalCapturesBySyntax.Add(oldCapture.DeclaringSyntaxReferences.Single().GetSyntax(cancellationToken), i); } } for (var newCaptureIndex = 0; newCaptureIndex < newCaptures.Length; newCaptureIndex++) { var newCapture = newCaptures[newCaptureIndex]; int oldCaptureIndex; if (newCapture.Kind == SymbolKind.Parameter) { var newParameterCapture = (IParameterSymbol)newCapture; var newParameterKey = GetParameterKey(newParameterCapture, cancellationToken); if (!TryMapParameter(newParameterKey, map.Reverse, out var oldParameterKey) || !oldParameterCapturesByLambdaAndOrdinal.TryGetValue(oldParameterKey, out oldCaptureIndex)) { // parameter has not been captured prior the edit: diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.CapturingVariable, GetVariableDiagnosticSpan(newCapture), null, new[] { newCapture.Name })); hasErrors = true; continue; } // Remove the old parameter capture so that at the end we can use this hashset // to identify old captures that don't have a corresponding capture in the new version: oldParameterCapturesByLambdaAndOrdinal.Remove(oldParameterKey); } else { var newCaptureSyntax = newCapture.DeclaringSyntaxReferences.Single().GetSyntax(cancellationToken); // variable doesn't exists in the old method or has not been captured prior the edit: if (!map.Reverse.TryGetValue(newCaptureSyntax, out var mappedOldSyntax) || !oldLocalCapturesBySyntax.TryGetValue(mappedOldSyntax, out oldCaptureIndex)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.CapturingVariable, newCapture.Locations.First().SourceSpan, null, new[] { newCapture.Name })); hasErrors = true; continue; } // Remove the old capture so that at the end we can use this hashset // to identify old captures that don't have a corresponding capture in the new version: oldLocalCapturesBySyntax.Remove(mappedOldSyntax); } reverseCapturesMap[newCaptureIndex] = oldCaptureIndex; // the type and scope of parameters can't change if (newCapture.Kind == SymbolKind.Parameter) { continue; } var oldCapture = oldCaptures[oldCaptureIndex]; // Parameter capture can't be changed to local capture and vice versa // because parameters can't be introduced or deleted during EnC // (we checked above for changes in lambda signatures). // Also range variables can't be mapped to other variables since they have // different kinds of declarator syntax nodes. Debug.Assert(oldCapture.Kind == newCapture.Kind); // Range variables don't have types. Each transparent identifier (range variable use) // might have a different type. Changing these types is ok as long as the containing lambda // signatures remain unchanged, which we validate for all lambdas in general. // // The scope of a transparent identifier is the containing lambda body. Since we verify that // each lambda body accesses the same captured variables (including range variables) // the corresponding scopes are guaranteed to be preserved as well. if (oldCapture.Kind == SymbolKind.RangeVariable) { continue; } // rename: // Note that the name has to match exactly even in VB, since we can't rename a field. // Consider: We could allow rename by emitting some special debug info for the field. if (newCapture.Name != oldCapture.Name) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.RenamingCapturedVariable, newCapture.Locations.First().SourceSpan, null, new[] { oldCapture.Name, newCapture.Name })); hasErrors = true; continue; } // type check var oldTypeOpt = GetType(oldCapture); var newTypeOpt = GetType(newCapture); if (!TypesEquivalent(oldTypeOpt, newTypeOpt, exact: false)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingCapturedVariableType, GetVariableDiagnosticSpan(newCapture), null, new[] { newCapture.Name, oldTypeOpt.ToDisplayString(ErrorDisplayFormat) })); hasErrors = true; continue; } // scope check: var oldScopeOpt = GetCapturedVariableScope(oldCapture, oldMemberBody, cancellationToken); var newScopeOpt = GetCapturedVariableScope(newCapture, newMemberBody, cancellationToken); if (!AreEquivalentClosureScopes(oldScopeOpt, newScopeOpt, map.Reverse)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingCapturedVariableScope, GetVariableDiagnosticSpan(newCapture), null, new[] { newCapture.Name })); hasErrors = true; continue; } newCapturesToClosureScopes[newCaptureIndex] = newScopeOpt; oldCapturesToClosureScopes[oldCaptureIndex] = oldScopeOpt; } // What's left in oldCapturesBySyntax are captured variables in the previous version // that have no corresponding captured variables in the new version. // Report a rude edit for all such variables. if (oldParameterCapturesByLambdaAndOrdinal.Count > 0) { // syntax-less parameters are not included: var newMemberParametersWithSyntax = newMember.GetParameters(); // uncaptured parameters: foreach (var ((oldContainingLambdaSyntax, ordinal), oldCaptureIndex) in oldParameterCapturesByLambdaAndOrdinal) { var oldCapture = oldCaptures[oldCaptureIndex]; TextSpan span; if (ordinal < 0) { // this parameter: span = GetThisParameterDiagnosticSpan(newMember); } else if (oldContainingLambdaSyntax != null) { // lambda: span = GetLambdaParameterDiagnosticSpan(oldContainingLambdaSyntax, ordinal); } else if (oldCapture.IsImplicitValueParameter()) { // value parameter of a property/indexer setter, event adder/remover: span = newMember.Locations.First().SourceSpan; } else { // method or property: span = GetVariableDiagnosticSpan(newMemberParametersWithSyntax[ordinal]); } diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.NotCapturingVariable, span, null, new[] { oldCapture.Name })); } hasErrors = true; } if (oldLocalCapturesBySyntax.Count > 0) { // uncaptured or deleted variables: foreach (var entry in oldLocalCapturesBySyntax) { var oldCaptureNode = entry.Key; var oldCaptureIndex = entry.Value; var name = oldCaptures[oldCaptureIndex].Name; if (map.Forward.TryGetValue(oldCaptureNode, out var newCaptureNode)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.NotCapturingVariable, newCaptureNode.Span, null, new[] { name })); } else { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.DeletingCapturedVariable, GetDeletedNodeDiagnosticSpan(map.Forward, oldCaptureNode), null, new[] { name })); } } hasErrors = true; } } private void ReportLambdaSignatureRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, SemanticModel oldModel, SyntaxNode oldLambdaBody, SemanticModel newModel, SyntaxNode newLambdaBody, EditAndContinueCapabilities capabilities, out bool hasSignatureErrors, CancellationToken cancellationToken) { hasSignatureErrors = false; var newLambda = GetLambda(newLambdaBody); var oldLambda = GetLambda(oldLambdaBody); Debug.Assert(IsNestedFunction(newLambda) == IsNestedFunction(oldLambda)); // queries are analyzed separately if (!IsNestedFunction(newLambda)) { return; } if (IsLocalFunction(oldLambda) != IsLocalFunction(newLambda)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.SwitchBetweenLambdaAndLocalFunction, newLambda); hasSignatureErrors = true; return; } var oldLambdaSymbol = GetLambdaExpressionSymbol(oldModel, oldLambda, cancellationToken); var newLambdaSymbol = GetLambdaExpressionSymbol(newModel, newLambda, cancellationToken); // signature validation: if (!ParametersEquivalent(oldLambdaSymbol.Parameters, newLambdaSymbol.Parameters, exact: false)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingLambdaParameters, newLambda); hasSignatureErrors = true; } else if (!ReturnTypesEquivalent(oldLambdaSymbol, newLambdaSymbol, exact: false)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingLambdaReturnType, newLambda); hasSignatureErrors = true; } else if (!TypeParametersEquivalent(oldLambdaSymbol.TypeParameters, newLambdaSymbol.TypeParameters, exact: false)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingTypeParameters, newLambda); hasSignatureErrors = true; } if (hasSignatureErrors) { return; } // custom attributes ReportCustomAttributeRudeEdits(diagnostics, oldLambdaSymbol, newLambdaSymbol, newLambda, newModel.Compilation, capabilities, out _, out _, cancellationToken); for (var i = 0; i < oldLambdaSymbol.Parameters.Length; i++) { ReportCustomAttributeRudeEdits(diagnostics, oldLambdaSymbol.Parameters[i], newLambdaSymbol.Parameters[i], newLambda, newModel.Compilation, capabilities, out _, out _, cancellationToken); } for (var i = 0; i < oldLambdaSymbol.TypeParameters.Length; i++) { ReportCustomAttributeRudeEdits(diagnostics, oldLambdaSymbol.TypeParameters[i], newLambdaSymbol.TypeParameters[i], newLambda, newModel.Compilation, capabilities, out _, out _, cancellationToken); } } private static ITypeSymbol GetType(ISymbol localOrParameter) => localOrParameter.Kind switch { SymbolKind.Parameter => ((IParameterSymbol)localOrParameter).Type, SymbolKind.Local => ((ILocalSymbol)localOrParameter).Type, _ => throw ExceptionUtilities.UnexpectedValue(localOrParameter.Kind), }; private SyntaxNode GetCapturedVariableScope(ISymbol localOrParameter, SyntaxNode memberBody, CancellationToken cancellationToken) { Debug.Assert(localOrParameter.Kind != SymbolKind.RangeVariable); if (localOrParameter.Kind == SymbolKind.Parameter) { var member = localOrParameter.ContainingSymbol; // lambda parameters and C# constructor parameters are lifted to their own scope: if ((member as IMethodSymbol)?.MethodKind == MethodKind.AnonymousFunction || HasParameterClosureScope(member)) { var result = localOrParameter.DeclaringSyntaxReferences.Single().GetSyntax(cancellationToken); Debug.Assert(IsLambda(result)); return result; } return memberBody; } var node = localOrParameter.DeclaringSyntaxReferences.Single().GetSyntax(cancellationToken); while (true) { RoslynDebug.Assert(node is object); if (IsClosureScope(node)) { return node; } node = node.Parent; } } private static bool AreEquivalentClosureScopes(SyntaxNode oldScopeOpt, SyntaxNode newScopeOpt, IReadOnlyDictionary<SyntaxNode, SyntaxNode> reverseMap) { if (oldScopeOpt == null || newScopeOpt == null) { return oldScopeOpt == newScopeOpt; } return reverseMap.TryGetValue(newScopeOpt, out var mappedScope) && mappedScope == oldScopeOpt; } #endregion #region State Machines private void ReportStateMachineRudeEdits( Compilation oldCompilation, ISymbol oldMember, SyntaxNode newBody, ArrayBuilder<RudeEditDiagnostic> diagnostics) { // Only methods, local functions and anonymous functions can be async/iterators machines, // but don't assume so to be resiliant against errors in code. if (oldMember is not IMethodSymbol oldMethod) { return; } var stateMachineAttributeQualifiedName = oldMethod.IsAsync ? "System.Runtime.CompilerServices.AsyncStateMachineAttribute" : "System.Runtime.CompilerServices.IteratorStateMachineAttribute"; // We assume that the attributes, if exist, are well formed. // If not an error will be reported during EnC delta emit. // Report rude edit if the type is not found in the compilation. // Consider: This diagnostic is cached in the document analysis, // so it could happen that the attribute type is added later to // the compilation and we continue to report the diagnostic. // We could report rude edit when adding these types or flush all // (or specific) document caches. This is not a common scenario though, // since the attribute has been long defined in the BCL. if (oldCompilation.GetTypeByMetadataName(stateMachineAttributeQualifiedName) == null) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.UpdatingStateMachineMethodMissingAttribute, GetBodyDiagnosticSpan(newBody, EditKind.Update), newBody, new[] { stateMachineAttributeQualifiedName })); } } #endregion #endregion #region Helpers private static SyntaxNode? TryGetNode(SyntaxNode root, int position) => root.FullSpan.Contains(position) ? root.FindToken(position).Parent : null; internal static void AddNodes<T>(ArrayBuilder<SyntaxNode> nodes, SyntaxList<T> list) where T : SyntaxNode { foreach (var node in list) { nodes.Add(node); } } internal static void AddNodes<T>(ArrayBuilder<SyntaxNode> nodes, SeparatedSyntaxList<T>? list) where T : SyntaxNode { if (list.HasValue) { foreach (var node in list.Value) { nodes.Add(node); } } } private sealed class TypedConstantComparer : IEqualityComparer<TypedConstant> { public static TypedConstantComparer Instance = new TypedConstantComparer(); public bool Equals(TypedConstant x, TypedConstant y) => x.Kind.Equals(y.Kind) && x.IsNull.Equals(y.IsNull) && SymbolEquivalenceComparer.Instance.Equals(x.Type, y.Type) && x.Kind switch { TypedConstantKind.Array => x.Values.SequenceEqual(y.Values, TypedConstantComparer.Instance), _ => object.Equals(x.Value, y.Value) }; public int GetHashCode(TypedConstant obj) => obj.GetHashCode(); } private sealed class NamedArgumentComparer : IEqualityComparer<KeyValuePair<string, TypedConstant>> { public static NamedArgumentComparer Instance = new NamedArgumentComparer(); public bool Equals(KeyValuePair<string, TypedConstant> x, KeyValuePair<string, TypedConstant> y) => x.Key.Equals(y.Key) && TypedConstantComparer.Instance.Equals(x.Value, y.Value); public int GetHashCode(KeyValuePair<string, TypedConstant> obj) => obj.GetHashCode(); } #pragma warning disable format private static bool IsGlobalMain(ISymbol symbol) => symbol is IMethodSymbol { Name: WellKnownMemberNames.TopLevelStatementsEntryPointMethodName, ContainingType.Name: WellKnownMemberNames.TopLevelStatementsEntryPointTypeName }; #pragma warning restore format private static bool InGenericContext(ISymbol symbol, out bool isGenericMethod) { var current = symbol; while (true) { if (current is IMethodSymbol { Arity: > 0 }) { isGenericMethod = true; return true; } if (current is INamedTypeSymbol { Arity: > 0 }) { isGenericMethod = false; return true; } current = current.ContainingSymbol; if (current == null) { isGenericMethod = false; return false; } } } #endregion #region Testing internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly AbstractEditAndContinueAnalyzer _abstractEditAndContinueAnalyzer; public TestAccessor(AbstractEditAndContinueAnalyzer abstractEditAndContinueAnalyzer) => _abstractEditAndContinueAnalyzer = abstractEditAndContinueAnalyzer; internal void ReportTopLevelSyntacticRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, EditScript<SyntaxNode> syntacticEdits, Dictionary<SyntaxNode, EditKind> editMap) => _abstractEditAndContinueAnalyzer.ReportTopLevelSyntacticRudeEdits(diagnostics, syntacticEdits, editMap); internal BidirectionalMap<SyntaxNode> ComputeMap( Match<SyntaxNode> bodyMatch, ArrayBuilder<ActiveNode> activeNodes, ref Dictionary<SyntaxNode, LambdaInfo>? lazyActiveOrMatchedLambdas, ArrayBuilder<RudeEditDiagnostic> diagnostics) { return _abstractEditAndContinueAnalyzer.ComputeMap(bodyMatch, activeNodes, ref lazyActiveOrMatchedLambdas, diagnostics); } internal Match<SyntaxNode> ComputeBodyMatch( SyntaxNode oldBody, SyntaxNode newBody, ActiveNode[] activeNodes, ArrayBuilder<RudeEditDiagnostic> diagnostics, out bool oldHasStateMachineSuspensionPoint, out bool newHasStateMachineSuspensionPoint) { return _abstractEditAndContinueAnalyzer.ComputeBodyMatch(oldBody, newBody, activeNodes, diagnostics, out oldHasStateMachineSuspensionPoint, out newHasStateMachineSuspensionPoint); } } #endregion } }
1
dotnet/roslyn
55,409
Use FixedSize API
tmat
2021-08-04T19:30:40Z
2021-08-04T21:53:46Z
e0112742bff208dd0546de45e36f7b52058a45a3
c90bf0ec986010051662c8e1fbc872c2fd86bc4e
Use FixedSize API.
./src/Features/VisualBasic/Portable/EditAndContinue/VisualBasicEditAndContinueAnalyzer.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.Differencing Imports Microsoft.CodeAnalysis.EditAndContinue Imports Microsoft.CodeAnalysis.Host Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.EditAndContinue Friend NotInheritable Class VisualBasicEditAndContinueAnalyzer Inherits AbstractEditAndContinueAnalyzer <ExportLanguageServiceFactory(GetType(IEditAndContinueAnalyzer), LanguageNames.VisualBasic), [Shared]> Private NotInheritable Class Factory Implements ILanguageServiceFactory <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Function CreateLanguageService(languageServices As HostLanguageServices) As ILanguageService Implements ILanguageServiceFactory.CreateLanguageService Return New VisualBasicEditAndContinueAnalyzer(testFaultInjector:=Nothing) End Function End Class ' Public for testing purposes Public Sub New(Optional testFaultInjector As Action(Of SyntaxNode) = Nothing) MyBase.New(testFaultInjector) End Sub #Region "Syntax Analysis" Friend Overrides Function TryFindMemberDeclaration(rootOpt As SyntaxNode, node As SyntaxNode, <Out> ByRef declarations As OneOrMany(Of SyntaxNode)) As Boolean Dim current = node While current IsNot rootOpt Select Case current.Kind Case SyntaxKind.SubBlock, SyntaxKind.FunctionBlock, SyntaxKind.ConstructorBlock, SyntaxKind.OperatorBlock, SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock declarations = OneOrMany.Create(current) Return True Case SyntaxKind.PropertyStatement ' Property a As Integer = 1 ' Property a As New T If Not current.Parent.IsKind(SyntaxKind.PropertyBlock) Then declarations = OneOrMany.Create(current) Return True End If Case SyntaxKind.VariableDeclarator If current.Parent.IsKind(SyntaxKind.FieldDeclaration) Then Dim variableDeclarator = CType(current, VariableDeclaratorSyntax) If variableDeclarator.Names.Count = 1 Then declarations = OneOrMany.Create(current) Else declarations = OneOrMany.Create(variableDeclarator.Names.SelectAsArray(Function(n) CType(n, SyntaxNode))) End If Return True End If Case SyntaxKind.ModifiedIdentifier If current.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration) Then declarations = OneOrMany.Create(current) Return True End If End Select current = current.Parent End While declarations = Nothing Return False End Function ''' <summary> ''' Returns true if the <see cref="ModifiedIdentifierSyntax"/> node represents a field declaration. ''' </summary> Private Shared Function IsFieldDeclaration(node As ModifiedIdentifierSyntax) As Boolean Return node.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration) AndAlso DirectCast(node.Parent, VariableDeclaratorSyntax).Names.Count > 1 End Function ''' <summary> ''' Returns true if the <see cref="VariableDeclaratorSyntax"/> node represents a field declaration. ''' </summary> Private Shared Function IsFieldDeclaration(node As VariableDeclaratorSyntax) As Boolean Return node.Parent.IsKind(SyntaxKind.FieldDeclaration) AndAlso node.Names.Count = 1 End Function ''' <returns> ''' Given a node representing a declaration or a top-level edit node returns: ''' - <see cref="MethodBlockBaseSyntax"/> for methods, constructors, operators and accessors. ''' - <see cref="ExpressionSyntax"/> for auto-properties and fields with initializer or AsNew clause. ''' - <see cref="ArgumentListSyntax"/> for fields with array initializer, e.g. "Dim a(1) As Integer". ''' A null reference otherwise. ''' </returns> Friend Overrides Function TryGetDeclarationBody(node As SyntaxNode) As SyntaxNode Select Case node.Kind Case SyntaxKind.SubBlock, SyntaxKind.FunctionBlock, SyntaxKind.ConstructorBlock, SyntaxKind.OperatorBlock, SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock ' the body is the Statements list of the block Return node Case SyntaxKind.PropertyStatement ' the body is the initializer expression/new expression (if any) Dim propertyStatement = DirectCast(node, PropertyStatementSyntax) If propertyStatement.Initializer IsNot Nothing Then Return propertyStatement.Initializer.Value End If If HasAsNewClause(propertyStatement) Then Return DirectCast(propertyStatement.AsClause, AsNewClauseSyntax).NewExpression End If Return Nothing Case SyntaxKind.VariableDeclarator If Not node.Parent.IsKind(SyntaxKind.FieldDeclaration) Then Return Nothing End If Dim variableDeclarator = DirectCast(node, VariableDeclaratorSyntax) Dim body As SyntaxNode = Nothing If variableDeclarator.Initializer IsNot Nothing Then ' Dim a = initializer body = variableDeclarator.Initializer.Value ElseIf HasAsNewClause(variableDeclarator) Then ' Dim a As New T ' Dim a,b As New T body = DirectCast(variableDeclarator.AsClause, AsNewClauseSyntax).NewExpression End If ' Dim a(n) As T If variableDeclarator.Names.Count = 1 Then Dim name = variableDeclarator.Names(0) If name.ArrayBounds IsNot Nothing Then ' Initializer and AsNew clause can't be syntactically specified at the same time, but array bounds can be (it's a semantic error). ' Guard against such case to maintain consistency and set body to Nothing in that case. body = If(body Is Nothing, name.ArrayBounds, Nothing) End If End If Return body Case SyntaxKind.ModifiedIdentifier If Not node.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration) Then Return Nothing End If Dim modifiedIdentifier = CType(node, ModifiedIdentifierSyntax) Dim body As SyntaxNode = Nothing ' Dim a, b As New C() Dim variableDeclarator = DirectCast(node.Parent, VariableDeclaratorSyntax) If HasAsNewClause(variableDeclarator) Then body = DirectCast(variableDeclarator.AsClause, AsNewClauseSyntax).NewExpression End If ' Dim a(n) As Integer ' Dim a(n), b(n) As Integer If modifiedIdentifier.ArrayBounds IsNot Nothing Then ' AsNew clause can be syntactically specified at the same time as array bounds can be (it's a semantic error). ' Guard against such case to maintain consistency and set body to Nothing in that case. body = If(body Is Nothing, modifiedIdentifier.ArrayBounds, Nothing) End If Return body Case Else ' Note: A method without body is represented by a SubStatement. Return Nothing End Select End Function Friend Overrides Function IsDeclarationWithSharedBody(declaration As SyntaxNode) As Boolean If declaration.Kind = SyntaxKind.ModifiedIdentifier AndAlso declaration.Parent.Kind = SyntaxKind.VariableDeclarator Then Dim variableDeclarator = CType(declaration.Parent, VariableDeclaratorSyntax) Return variableDeclarator.Names.Count > 1 AndAlso variableDeclarator.Initializer IsNot Nothing OrElse HasAsNewClause(variableDeclarator) End If Return False End Function Protected Overrides Function GetCapturedVariables(model As SemanticModel, memberBody As SyntaxNode) As ImmutableArray(Of ISymbol) Dim methodBlock = TryCast(memberBody, MethodBlockBaseSyntax) If methodBlock IsNot Nothing Then If methodBlock.Statements.IsEmpty Then Return ImmutableArray(Of ISymbol).Empty End If Return model.AnalyzeDataFlow(methodBlock.Statements.First, methodBlock.Statements.Last).Captured End If Dim expression = TryCast(memberBody, ExpressionSyntax) If expression IsNot Nothing Then Return model.AnalyzeDataFlow(expression).Captured End If ' Edge case, no need to be efficient, currently there can either be no captured variables or just "Me". ' Dim a((Function(n) n + 1).Invoke(1), (Function(n) n + 2).Invoke(2)) As Integer Dim arrayBounds = TryCast(memberBody, ArgumentListSyntax) If arrayBounds IsNot Nothing Then Return ImmutableArray.CreateRange( arrayBounds.Arguments. SelectMany(AddressOf GetArgumentExpressions). SelectMany(Function(expr) model.AnalyzeDataFlow(expr).Captured). Distinct()) End If Throw ExceptionUtilities.UnexpectedValue(memberBody) End Function Private Shared Iterator Function GetArgumentExpressions(argument As ArgumentSyntax) As IEnumerable(Of ExpressionSyntax) Select Case argument.Kind Case SyntaxKind.SimpleArgument Yield DirectCast(argument, SimpleArgumentSyntax).Expression Case SyntaxKind.RangeArgument Dim range = DirectCast(argument, RangeArgumentSyntax) Yield range.LowerBound Yield range.UpperBound Case SyntaxKind.OmittedArgument Case Else Throw ExceptionUtilities.UnexpectedValue(argument.Kind) End Select End Function Friend Overrides Function HasParameterClosureScope(member As ISymbol) As Boolean Return False End Function Protected Overrides Function GetVariableUseSites(roots As IEnumerable(Of SyntaxNode), localOrParameter As ISymbol, model As SemanticModel, cancellationToken As CancellationToken) As IEnumerable(Of SyntaxNode) Debug.Assert(TypeOf localOrParameter Is IParameterSymbol OrElse TypeOf localOrParameter Is ILocalSymbol OrElse TypeOf localOrParameter Is IRangeVariableSymbol) ' Not supported (it's non trivial to find all places where "this" is used): Debug.Assert(Not localOrParameter.IsThisParameter()) Return From root In roots From node In root.DescendantNodesAndSelf() Where node.IsKind(SyntaxKind.IdentifierName) Let identifier = DirectCast(node, IdentifierNameSyntax) Where String.Equals(DirectCast(identifier.Identifier.Value, String), localOrParameter.Name, StringComparison.OrdinalIgnoreCase) AndAlso If(model.GetSymbolInfo(identifier, cancellationToken).Symbol?.Equals(localOrParameter), False) Select node End Function Private Shared Function HasAsNewClause(variableDeclarator As VariableDeclaratorSyntax) As Boolean Return variableDeclarator.AsClause IsNot Nothing AndAlso variableDeclarator.AsClause.IsKind(SyntaxKind.AsNewClause) End Function Private Shared Function HasAsNewClause(propertyStatement As PropertyStatementSyntax) As Boolean Return propertyStatement.AsClause IsNot Nothing AndAlso propertyStatement.AsClause.IsKind(SyntaxKind.AsNewClause) End Function ''' <returns> ''' Methods, operators, constructors, property and event accessors: ''' - We need to return the entire block declaration since the Begin and End statements are covered by breakpoint spans. ''' Field declarations in form of "Dim a, b, c As New C()" ''' - Breakpoint spans cover "a", "b" and "c" and also "New C()" since the expression may contain lambdas. ''' For simplicity we don't allow moving the new expression independently of the field name. ''' Field declarations with array initializers "Dim a(n), b(n) As Integer" ''' - Breakpoint spans cover "a(n)" and "b(n)". ''' </returns> Friend Overrides Function TryGetActiveTokens(node As SyntaxNode) As IEnumerable(Of SyntaxToken) Select Case node.Kind Case SyntaxKind.SubBlock, SyntaxKind.FunctionBlock, SyntaxKind.ConstructorBlock, SyntaxKind.OperatorBlock, SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock ' the body is the Statements list of the block Return node.DescendantTokens() Case SyntaxKind.PropertyStatement ' Property: Attributes Modifiers [|Identifier AsClause Initializer|] ImplementsClause ' Property: Attributes Modifiers [|Identifier$ Initializer|] ImplementsClause Dim propertyStatement = DirectCast(node, PropertyStatementSyntax) If propertyStatement.Initializer IsNot Nothing Then Return SpecializedCollections.SingletonEnumerable(propertyStatement.Identifier).Concat(If(propertyStatement.AsClause?.DescendantTokens(), Array.Empty(Of SyntaxToken))).Concat(propertyStatement.Initializer.DescendantTokens()) End If If HasAsNewClause(propertyStatement) Then Return SpecializedCollections.SingletonEnumerable(propertyStatement.Identifier).Concat(propertyStatement.AsClause.DescendantTokens()) End If Return Nothing Case SyntaxKind.VariableDeclarator Dim variableDeclarator = DirectCast(node, VariableDeclaratorSyntax) If Not IsFieldDeclaration(variableDeclarator) Then Return Nothing End If ' Field: Attributes Modifiers Declarators Dim fieldDeclaration = DirectCast(node.Parent, FieldDeclarationSyntax) If fieldDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword) Then Return Nothing End If ' Dim a = initializer If variableDeclarator.Initializer IsNot Nothing Then Return variableDeclarator.DescendantTokens() End If ' Dim a As New C() If HasAsNewClause(variableDeclarator) Then Return variableDeclarator.DescendantTokens() End If ' Dim a(n) As Integer Dim modifiedIdentifier = variableDeclarator.Names.Single() If modifiedIdentifier.ArrayBounds IsNot Nothing Then Return variableDeclarator.DescendantTokens() End If Return Nothing Case SyntaxKind.ModifiedIdentifier Dim modifiedIdentifier = DirectCast(node, ModifiedIdentifierSyntax) If Not IsFieldDeclaration(modifiedIdentifier) Then Return Nothing End If ' Dim a, b As New C() Dim variableDeclarator = DirectCast(node.Parent, VariableDeclaratorSyntax) If HasAsNewClause(variableDeclarator) Then Return node.DescendantTokens().Concat(DirectCast(variableDeclarator.AsClause, AsNewClauseSyntax).NewExpression.DescendantTokens()) End If ' Dim a(n), b(n) As Integer If modifiedIdentifier.ArrayBounds IsNot Nothing Then Return node.DescendantTokens() End If Return Nothing Case Else Return Nothing End Select End Function Friend Overrides Function GetActiveSpanEnvelope(declaration As SyntaxNode) As (envelope As TextSpan, hole As TextSpan) Select Case declaration.Kind Case SyntaxKind.SubBlock, SyntaxKind.FunctionBlock, SyntaxKind.ConstructorBlock, SyntaxKind.OperatorBlock, SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock ' the body is the Statements list of the block Return (declaration.Span, Nothing) Case SyntaxKind.PropertyStatement ' Property: Attributes Modifiers [|Identifier AsClause Initializer|] ImplementsClause ' Property: Attributes Modifiers [|Identifier$ Initializer|] ImplementsClause Dim propertyStatement = DirectCast(declaration, PropertyStatementSyntax) If propertyStatement.Initializer IsNot Nothing Then Return (TextSpan.FromBounds(propertyStatement.Identifier.Span.Start, propertyStatement.Initializer.Span.End), Nothing) End If If HasAsNewClause(propertyStatement) Then Return (TextSpan.FromBounds(propertyStatement.Identifier.Span.Start, propertyStatement.AsClause.Span.End), Nothing) End If Return Nothing Case SyntaxKind.VariableDeclarator Dim variableDeclarator = DirectCast(declaration, VariableDeclaratorSyntax) If Not declaration.Parent.IsKind(SyntaxKind.FieldDeclaration) OrElse variableDeclarator.Names.Count > 1 Then Return Nothing End If ' Field: Attributes Modifiers Declarators Dim fieldDeclaration = DirectCast(declaration.Parent, FieldDeclarationSyntax) If fieldDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword) Then Return Nothing End If ' Dim a = initializer If variableDeclarator.Initializer IsNot Nothing Then Return (variableDeclarator.Span, Nothing) End If ' Dim a As New C() If HasAsNewClause(variableDeclarator) Then Return (variableDeclarator.Span, Nothing) End If ' Dim a(n) As Integer Dim modifiedIdentifier = variableDeclarator.Names.Single() If modifiedIdentifier.ArrayBounds IsNot Nothing Then Return (variableDeclarator.Span, Nothing) End If Return Nothing Case SyntaxKind.ModifiedIdentifier If Not declaration.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration) Then Return Nothing End If ' Dim a, b As New C() Dim variableDeclarator = DirectCast(declaration.Parent, VariableDeclaratorSyntax) If HasAsNewClause(variableDeclarator) Then Dim asNewClause = DirectCast(variableDeclarator.AsClause, AsNewClauseSyntax) Return (envelope:=TextSpan.FromBounds(declaration.Span.Start, asNewClause.NewExpression.Span.End), hole:=TextSpan.FromBounds(declaration.Span.End, asNewClause.NewExpression.Span.Start)) End If ' Dim a(n) As Integer ' Dim a(n), b(n) As Integer Dim modifiedIdentifier = DirectCast(declaration, ModifiedIdentifierSyntax) If modifiedIdentifier.ArrayBounds IsNot Nothing Then Return (declaration.Span, Nothing) End If Return Nothing Case Else Return Nothing End Select End Function Protected Overrides Function GetEncompassingAncestorImpl(bodyOrMatchRoot As SyntaxNode) As SyntaxNode ' AsNewClause is a match root for field/property As New initializer ' EqualsClause is a match root for field/property initializer If bodyOrMatchRoot.IsKind(SyntaxKind.AsNewClause) OrElse bodyOrMatchRoot.IsKind(SyntaxKind.EqualsValue) Then Debug.Assert(bodyOrMatchRoot.Parent.IsKind(SyntaxKind.VariableDeclarator) OrElse bodyOrMatchRoot.Parent.IsKind(SyntaxKind.PropertyStatement)) Return bodyOrMatchRoot.Parent End If ' ArgumentList is a match root for an array initialized field If bodyOrMatchRoot.IsKind(SyntaxKind.ArgumentList) Then Debug.Assert(bodyOrMatchRoot.Parent.IsKind(SyntaxKind.ModifiedIdentifier)) Return bodyOrMatchRoot.Parent End If ' The following active nodes are outside of the initializer body, ' we need to return a node that encompasses them. ' Dim [|a = <<Body>>|] ' Dim [|a As Integer = <<Body>>|] ' Dim [|a As <<Body>>|] ' Dim [|a|], [|b|], [|c|] As <<Body>> ' Property [|P As Integer = <<Body>>|] ' Property [|P As <<Body>>|] If bodyOrMatchRoot.Parent.IsKind(SyntaxKind.AsNewClause) OrElse bodyOrMatchRoot.Parent.IsKind(SyntaxKind.EqualsValue) Then Return bodyOrMatchRoot.Parent.Parent End If Return bodyOrMatchRoot End Function Protected Overrides Function FindStatementAndPartner(declarationBody As SyntaxNode, span As TextSpan, partnerDeclarationBodyOpt As SyntaxNode, <Out> ByRef partnerOpt As SyntaxNode, <Out> ByRef statementPart As Integer) As SyntaxNode Dim position = span.Start SyntaxUtilities.AssertIsBody(declarationBody, allowLambda:=False) Debug.Assert(partnerDeclarationBodyOpt Is Nothing OrElse partnerDeclarationBodyOpt.RawKind = declarationBody.RawKind) ' Only field and property initializers may have an [|active statement|] starting outside of the <<body>>. ' Simple field initializers: Dim [|a = <<expr>>|] ' Dim [|a As Integer = <<expr>>|] ' Dim [|a = <<expr>>|], [|b = <<expr>>|], [|c As Integer = <<expr>>|] ' Dim [|a As <<New C>>|] ' Array initialized fields: Dim [|a<<(array bounds)>>|] As Integer ' Shared initializers: Dim [|a|], [|b|] As <<New C(Function() [|...|])>> ' Property initializers: Property [|p As Integer = <<body>>|] ' Property [|p As <<New C()>>|] If position < declarationBody.SpanStart Then If declarationBody.Parent.Parent.IsKind(SyntaxKind.PropertyStatement) Then ' Property [|p As Integer = <<body>>|] ' Property [|p As <<New C()>>|] If partnerDeclarationBodyOpt IsNot Nothing Then partnerOpt = partnerDeclarationBodyOpt.Parent.Parent End If Debug.Assert(declarationBody.Parent.Parent.IsKind(SyntaxKind.PropertyStatement)) Return declarationBody.Parent.Parent End If If declarationBody.IsKind(SyntaxKind.ArgumentList) Then ' Dim a<<ArgumentList>> As Integer If partnerDeclarationBodyOpt IsNot Nothing Then partnerOpt = partnerDeclarationBodyOpt.Parent End If Debug.Assert(declarationBody.Parent.IsKind(SyntaxKind.ModifiedIdentifier)) Return declarationBody.Parent End If If declarationBody.Parent.IsKind(SyntaxKind.AsNewClause) Then Dim variableDeclarator = DirectCast(declarationBody.Parent.Parent, VariableDeclaratorSyntax) If variableDeclarator.Names.Count > 1 Then ' Dim a, b, c As <<NewExpression>> Dim nameIndex = GetItemIndexByPosition(variableDeclarator.Names, position) If partnerDeclarationBodyOpt IsNot Nothing Then partnerOpt = DirectCast(partnerDeclarationBodyOpt.Parent.Parent, VariableDeclaratorSyntax).Names(nameIndex) End If Return variableDeclarator.Names(nameIndex) Else If partnerDeclarationBodyOpt IsNot Nothing Then partnerOpt = partnerDeclarationBodyOpt.Parent.Parent End If ' Dim a As <<NewExpression>> Return variableDeclarator End If End If If declarationBody.Parent.IsKind(SyntaxKind.EqualsValue) Then Debug.Assert(declarationBody.Parent.Parent.IsKind(SyntaxKind.VariableDeclarator) AndAlso declarationBody.Parent.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration)) If partnerDeclarationBodyOpt IsNot Nothing Then partnerOpt = partnerDeclarationBodyOpt.Parent.Parent End If Return declarationBody.Parent.Parent End If End If If Not declarationBody.FullSpan.Contains(position) Then ' invalid position, let's find a labeled node that encompasses the body: position = declarationBody.SpanStart End If Dim node As SyntaxNode = Nothing If partnerDeclarationBodyOpt IsNot Nothing Then SyntaxUtilities.FindLeafNodeAndPartner(declarationBody, position, partnerDeclarationBodyOpt, node, partnerOpt) Else node = declarationBody.FindToken(position).Parent partnerOpt = Nothing End If ' In some cases active statements may start at the same position. ' Consider a nested lambda: ' Function(a) [|[|Function(b)|] a + b|] ' There are 2 active statements, one spanning the the body of the outer lambda and ' the other on the nested lambda's header. ' Find the parent whose span starts at the same position but it's length is at least as long as the active span's length. While node.Span.Length < span.Length AndAlso node.Parent.SpanStart = position node = node.Parent partnerOpt = partnerOpt?.Parent End While Debug.Assert(node IsNot Nothing) While node IsNot declarationBody AndAlso Not SyntaxComparer.Statement.HasLabel(node) AndAlso Not LambdaUtilities.IsLambdaBodyStatementOrExpression(node) node = node.Parent If partnerOpt IsNot Nothing Then partnerOpt = partnerOpt.Parent End If End While ' In case of local variable declaration an active statement may start with a modified identifier. ' If it is a declaration with a simple initializer we want the resulting statement to be the declaration, ' not the identifier. If node.IsKind(SyntaxKind.ModifiedIdentifier) AndAlso node.Parent.IsKind(SyntaxKind.VariableDeclarator) AndAlso DirectCast(node.Parent, VariableDeclaratorSyntax).Names.Count = 1 Then node = node.Parent End If Return node End Function Friend Overrides Function FindDeclarationBodyPartner(leftDeclaration As SyntaxNode, rightDeclaration As SyntaxNode, leftNode As SyntaxNode) As SyntaxNode Debug.Assert(leftDeclaration.Kind = rightDeclaration.Kind) ' Special case modified identifiers with AsNew clause - the node we are seeking can be in the AsNew clause. If leftDeclaration.Kind = SyntaxKind.ModifiedIdentifier Then Dim leftDeclarator = CType(leftDeclaration.Parent, VariableDeclaratorSyntax) Dim rightDeclarator = CType(rightDeclaration.Parent, VariableDeclaratorSyntax) If leftDeclarator.AsClause IsNot Nothing AndAlso leftNode.SpanStart >= leftDeclarator.AsClause.SpanStart Then Return SyntaxUtilities.FindPartner(leftDeclarator.AsClause, rightDeclarator.AsClause, leftNode) End If End If Return SyntaxUtilities.FindPartner(leftDeclaration, rightDeclaration, leftNode) End Function Friend Overrides Function IsClosureScope(node As SyntaxNode) As Boolean Return LambdaUtilities.IsClosureScope(node) End Function Protected Overrides Function FindEnclosingLambdaBody(containerOpt As SyntaxNode, node As SyntaxNode) As SyntaxNode Dim root As SyntaxNode = GetEncompassingAncestor(containerOpt) While node IsNot root And node IsNot Nothing Dim body As SyntaxNode = Nothing If LambdaUtilities.IsLambdaBodyStatementOrExpression(node, body) Then Return body End If node = node.Parent End While Return Nothing End Function Protected Overrides Function TryGetPartnerLambdaBody(oldBody As SyntaxNode, newLambda As SyntaxNode) As SyntaxNode Return LambdaUtilities.GetCorrespondingLambdaBody(oldBody, newLambda) End Function Protected Overrides Function ComputeTopLevelMatch(oldCompilationUnit As SyntaxNode, newCompilationUnit As SyntaxNode) As Match(Of SyntaxNode) Return SyntaxComparer.TopLevel.ComputeMatch(oldCompilationUnit, newCompilationUnit) End Function Protected Overrides Function ComputeTopLevelDeclarationMatch(oldDeclaration As SyntaxNode, newDeclaration As SyntaxNode) As Match(Of SyntaxNode) Contract.ThrowIfNull(oldDeclaration.Parent) Contract.ThrowIfNull(newDeclaration.Parent) ' Allow matching field declarations represented by a identitifer and the whole variable declarator ' even when their node kinds do not match. If oldDeclaration.IsKind(SyntaxKind.ModifiedIdentifier) AndAlso newDeclaration.IsKind(SyntaxKind.VariableDeclarator) Then oldDeclaration = oldDeclaration.Parent ElseIf oldDeclaration.IsKind(SyntaxKind.VariableDeclarator) AndAlso newDeclaration.IsKind(SyntaxKind.ModifiedIdentifier) Then newDeclaration = newDeclaration.Parent End If Dim comparer = New SyntaxComparer(oldDeclaration.Parent, newDeclaration.Parent, {oldDeclaration}, {newDeclaration}) Return comparer.ComputeMatch(oldDeclaration.Parent, newDeclaration.Parent) End Function Protected Overrides Function ComputeBodyMatch(oldBody As SyntaxNode, newBody As SyntaxNode, knownMatches As IEnumerable(Of KeyValuePair(Of SyntaxNode, SyntaxNode))) As Match(Of SyntaxNode) SyntaxUtilities.AssertIsBody(oldBody, allowLambda:=True) SyntaxUtilities.AssertIsBody(newBody, allowLambda:=True) Debug.Assert((TypeOf oldBody.Parent Is LambdaExpressionSyntax) = (TypeOf oldBody.Parent Is LambdaExpressionSyntax)) Debug.Assert((TypeOf oldBody Is ExpressionSyntax) = (TypeOf newBody Is ExpressionSyntax)) Debug.Assert((TypeOf oldBody Is ArgumentListSyntax) = (TypeOf newBody Is ArgumentListSyntax)) If TypeOf oldBody.Parent Is LambdaExpressionSyntax Then ' The root is a single/multi line sub/function lambda. Return New SyntaxComparer(oldBody.Parent, newBody.Parent, oldBody.Parent.ChildNodes(), newBody.Parent.ChildNodes(), matchingLambdas:=True, compareStatementSyntax:=True). ComputeMatch(oldBody.Parent, newBody.Parent, knownMatches) End If If TypeOf oldBody Is ExpressionSyntax Then ' Dim a = <Expression> ' Dim a As <NewExpression> ' Dim a, b, c As <NewExpression> ' Queries: The root is a query clause, the body is the expression. Return New SyntaxComparer(oldBody.Parent, newBody.Parent, {oldBody}, {newBody}, matchingLambdas:=False, compareStatementSyntax:=True). ComputeMatch(oldBody.Parent, newBody.Parent, knownMatches) End If ' Method, accessor, operator, etc. bodies are represented by the declaring block, which is also the root. ' The body of an array initialized fields is an ArgumentListSyntax, which is the match root. Return SyntaxComparer.Statement.ComputeMatch(oldBody, newBody, knownMatches) End Function Protected Overrides Function TryMatchActiveStatement(oldStatement As SyntaxNode, statementPart As Integer, oldBody As SyntaxNode, newBody As SyntaxNode, <Out> ByRef newStatement As SyntaxNode) As Boolean SyntaxUtilities.AssertIsBody(oldBody, allowLambda:=True) SyntaxUtilities.AssertIsBody(newBody, allowLambda:=True) ' only statements in bodies of the same kind can be matched Debug.Assert((TypeOf oldBody Is MethodBlockBaseSyntax) = (TypeOf newBody Is MethodBlockBaseSyntax)) Debug.Assert((TypeOf oldBody Is ExpressionSyntax) = (TypeOf newBody Is ExpressionSyntax)) Debug.Assert((TypeOf oldBody Is ArgumentListSyntax) = (TypeOf newBody Is ArgumentListSyntax)) Debug.Assert((TypeOf oldBody Is LambdaHeaderSyntax) = (TypeOf newBody Is LambdaHeaderSyntax)) Debug.Assert(oldBody.Parent.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration) = newBody.Parent.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration)) Debug.Assert(oldBody.Parent.Parent.IsKind(SyntaxKind.PropertyStatement) = newBody.Parent.Parent.IsKind(SyntaxKind.PropertyStatement)) ' methods If TypeOf oldBody Is MethodBlockBaseSyntax Then newStatement = Nothing Return False End If ' lambdas If oldBody.IsKind(SyntaxKind.FunctionLambdaHeader) OrElse oldBody.IsKind(SyntaxKind.SubLambdaHeader) Then Dim oldSingleLineLambda = TryCast(oldBody.Parent, SingleLineLambdaExpressionSyntax) Dim newSingleLineLambda = TryCast(newBody.Parent, SingleLineLambdaExpressionSyntax) If oldSingleLineLambda IsNot Nothing AndAlso newSingleLineLambda IsNot Nothing AndAlso oldStatement Is oldSingleLineLambda.Body Then newStatement = newSingleLineLambda.Body Return True End If newStatement = Nothing Return False End If ' array initialized fields If newBody.IsKind(SyntaxKind.ArgumentList) Then ' the parent ModifiedIdentifier is the active statement If oldStatement Is oldBody.Parent Then newStatement = newBody.Parent Return True End If newStatement = Nothing Return False End If ' field and property initializers If TypeOf newBody Is ExpressionSyntax Then If newBody.Parent.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration) Then ' field Dim newDeclarator = DirectCast(newBody.Parent.Parent, VariableDeclaratorSyntax) Dim oldName As SyntaxToken If oldStatement.IsKind(SyntaxKind.VariableDeclarator) Then oldName = DirectCast(oldStatement, VariableDeclaratorSyntax).Names.Single.Identifier Else oldName = DirectCast(oldStatement, ModifiedIdentifierSyntax).Identifier End If For Each newName In newDeclarator.Names If SyntaxFactory.AreEquivalent(newName.Identifier, oldName) Then newStatement = newName Return True End If Next newStatement = Nothing Return False ElseIf newBody.Parent.Parent.IsKind(SyntaxKind.PropertyStatement) Then ' property If oldStatement Is oldBody.Parent.Parent Then newStatement = newBody.Parent.Parent Return True End If newStatement = newBody Return True End If End If ' queries If oldStatement Is oldBody Then newStatement = newBody Return True End If newStatement = Nothing Return False End Function #End Region #Region "Syntax And Semantic Utils" Protected Overrides Function GetGlobalStatementDiagnosticSpan(node As SyntaxNode) As TextSpan Return Nothing End Function Protected Overrides ReadOnly Property LineDirectiveKeyword As String Get Return "ExternalSource" End Get End Property Protected Overrides ReadOnly Property LineDirectiveSyntaxKind As UShort Get Return SyntaxKind.ExternalSourceDirectiveTrivia End Get End Property Protected Overrides Function GetSyntaxSequenceEdits(oldNodes As ImmutableArray(Of SyntaxNode), newNodes As ImmutableArray(Of SyntaxNode)) As IEnumerable(Of SequenceEdit) Return SyntaxComparer.GetSequenceEdits(oldNodes, newNodes) End Function Friend Overrides ReadOnly Property EmptyCompilationUnit As SyntaxNode Get Return SyntaxFactory.CompilationUnit() End Get End Property Friend Overrides Function ExperimentalFeaturesEnabled(tree As SyntaxTree) As Boolean ' There are no experimental features at this time. Return False End Function Protected Overrides Function StatementLabelEquals(node1 As SyntaxNode, node2 As SyntaxNode) As Boolean Return SyntaxComparer.Statement.GetLabelImpl(node1) = SyntaxComparer.Statement.GetLabelImpl(node2) End Function Private Shared Function GetItemIndexByPosition(Of TNode As SyntaxNode)(list As SeparatedSyntaxList(Of TNode), position As Integer) As Integer For i = list.SeparatorCount - 1 To 0 Step -1 If position > list.GetSeparator(i).SpanStart Then Return i + 1 End If Next Return 0 End Function Private Shared Function ChildrenCompiledInBody(node As SyntaxNode) As Boolean Return Not node.IsKind(SyntaxKind.MultiLineFunctionLambdaExpression) AndAlso Not node.IsKind(SyntaxKind.SingleLineFunctionLambdaExpression) AndAlso Not node.IsKind(SyntaxKind.MultiLineSubLambdaExpression) AndAlso Not node.IsKind(SyntaxKind.SingleLineSubLambdaExpression) End Function Protected Overrides Function TryGetEnclosingBreakpointSpan(root As SyntaxNode, position As Integer, <Out> ByRef span As TextSpan) As Boolean Return BreakpointSpans.TryGetEnclosingBreakpointSpan(root, position, minLength:=0, span) End Function Protected Overrides Function TryGetActiveSpan(node As SyntaxNode, statementPart As Integer, minLength As Integer, <Out> ByRef span As TextSpan) As Boolean Return BreakpointSpans.TryGetEnclosingBreakpointSpan(node, node.SpanStart, minLength, span) End Function Protected Overrides Iterator Function EnumerateNearStatements(statement As SyntaxNode) As IEnumerable(Of ValueTuple(Of SyntaxNode, Integer)) Dim direction As Integer = +1 Dim nodeOrToken As SyntaxNodeOrToken = statement Dim propertyOrFieldModifiers As SyntaxTokenList? = GetFieldOrPropertyModifiers(statement) While True ' If the current statement is the last statement of if-block or try-block statements ' pretend there are no siblings following it. Dim lastBlockStatement As SyntaxNode = Nothing If nodeOrToken.Parent IsNot Nothing Then If nodeOrToken.Parent.IsKind(SyntaxKind.MultiLineIfBlock) Then lastBlockStatement = DirectCast(nodeOrToken.Parent, MultiLineIfBlockSyntax).Statements.LastOrDefault() ElseIf nodeOrToken.Parent.IsKind(SyntaxKind.SingleLineIfStatement) Then lastBlockStatement = DirectCast(nodeOrToken.Parent, SingleLineIfStatementSyntax).Statements.LastOrDefault() ElseIf nodeOrToken.Parent.IsKind(SyntaxKind.TryBlock) Then lastBlockStatement = DirectCast(nodeOrToken.Parent, TryBlockSyntax).Statements.LastOrDefault() End If End If If direction > 0 Then If lastBlockStatement IsNot Nothing AndAlso nodeOrToken.AsNode() Is lastBlockStatement Then nodeOrToken = Nothing Else nodeOrToken = nodeOrToken.GetNextSibling() End If Else nodeOrToken = nodeOrToken.GetPreviousSibling() If lastBlockStatement IsNot Nothing AndAlso nodeOrToken.AsNode() Is lastBlockStatement Then nodeOrToken = Nothing End If End If If nodeOrToken.RawKind = 0 Then Dim parent = statement.Parent If parent Is Nothing Then Return End If If direction > 0 Then nodeOrToken = statement direction = -1 Continue While End If If propertyOrFieldModifiers.HasValue Then Yield (statement, -1) End If nodeOrToken = parent statement = parent propertyOrFieldModifiers = GetFieldOrPropertyModifiers(statement) direction = +1 End If Dim node = nodeOrToken.AsNode() If node Is Nothing Then Continue While End If If propertyOrFieldModifiers.HasValue Then Dim nodeModifiers = GetFieldOrPropertyModifiers(node) If Not nodeModifiers.HasValue OrElse propertyOrFieldModifiers.Value.Any(SyntaxKind.SharedKeyword) <> nodeModifiers.Value.Any(SyntaxKind.SharedKeyword) Then Continue While End If End If Yield (node, DefaultStatementPart) End While End Function Private Shared Function GetFieldOrPropertyModifiers(node As SyntaxNode) As SyntaxTokenList? If node.IsKind(SyntaxKind.FieldDeclaration) Then Return DirectCast(node, FieldDeclarationSyntax).Modifiers ElseIf node.IsKind(SyntaxKind.PropertyStatement) Then Return DirectCast(node, PropertyStatementSyntax).Modifiers Else Return Nothing End If End Function Protected Overrides Function AreEquivalent(left As SyntaxNode, right As SyntaxNode) As Boolean Return SyntaxFactory.AreEquivalent(left, right) End Function Private Shared Function AreEquivalentIgnoringLambdaBodies(left As SyntaxNode, right As SyntaxNode) As Boolean ' usual case If SyntaxFactory.AreEquivalent(left, right) Then Return True End If Return LambdaUtilities.AreEquivalentIgnoringLambdaBodies(left, right) End Function Protected Overrides Function AreEquivalentActiveStatements(oldStatement As SyntaxNode, newStatement As SyntaxNode, statementPart As Integer) As Boolean If oldStatement.RawKind <> newStatement.RawKind Then Return False End If ' Dim a,b,c As <NewExpression> ' We need to check the actual initializer expression in addition to the identifier. If HasMultiInitializer(oldStatement) Then Return AreEquivalentIgnoringLambdaBodies(oldStatement, newStatement) AndAlso AreEquivalentIgnoringLambdaBodies(DirectCast(oldStatement.Parent, VariableDeclaratorSyntax).AsClause, DirectCast(newStatement.Parent, VariableDeclaratorSyntax).AsClause) End If Select Case oldStatement.Kind Case SyntaxKind.SubNewStatement, SyntaxKind.SubStatement, SyntaxKind.SubNewStatement, SyntaxKind.FunctionStatement, SyntaxKind.OperatorStatement, SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorStatement, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorStatement ' Header statements are nops. Changes in the header statements are changes in top-level surface ' which should not be reported as active statement rude edits. Return True Case Else Return AreEquivalentIgnoringLambdaBodies(oldStatement, newStatement) End Select End Function Private Shared Function HasMultiInitializer(modifiedIdentifier As SyntaxNode) As Boolean Return modifiedIdentifier.Parent.IsKind(SyntaxKind.VariableDeclarator) AndAlso DirectCast(modifiedIdentifier.Parent, VariableDeclaratorSyntax).Names.Count > 1 End Function Friend Overrides Function IsInterfaceDeclaration(node As SyntaxNode) As Boolean Return node.IsKind(SyntaxKind.InterfaceBlock) End Function Friend Overrides Function IsRecordDeclaration(node As SyntaxNode) As Boolean ' No records in VB Return False End Function Friend Overrides Function TryGetContainingTypeDeclaration(node As SyntaxNode) As SyntaxNode Return node.Parent.FirstAncestorOrSelf(Of TypeBlockSyntax)() ' TODO: EnbumBlock? End Function Friend Overrides Function TryGetAssociatedMemberDeclaration(node As SyntaxNode, <Out> ByRef declaration As SyntaxNode) As Boolean If node.IsKind(SyntaxKind.Parameter, SyntaxKind.TypeParameter) Then Contract.ThrowIfFalse(node.IsParentKind(SyntaxKind.ParameterList, SyntaxKind.TypeParameterList)) declaration = node.Parent.Parent Return True End If If node.IsParentKind(SyntaxKind.PropertyBlock, SyntaxKind.EventBlock) Then declaration = node.Parent Return True End If declaration = Nothing Return False End Function Friend Overrides Function HasBackingField(propertyDeclaration As SyntaxNode) As Boolean Return SyntaxUtilities.HasBackingField(propertyDeclaration) End Function Friend Overrides Function IsDeclarationWithInitializer(declaration As SyntaxNode) As Boolean Select Case declaration.Kind Case SyntaxKind.VariableDeclarator Dim declarator = DirectCast(declaration, VariableDeclaratorSyntax) Return GetInitializerExpression(declarator.Initializer, declarator.AsClause) IsNot Nothing OrElse declarator.Names.Any(Function(n) n.ArrayBounds IsNot Nothing) Case SyntaxKind.ModifiedIdentifier Debug.Assert(declaration.Parent.IsKind(SyntaxKind.VariableDeclarator) OrElse declaration.Parent.IsKind(SyntaxKind.Parameter)) If Not declaration.Parent.IsKind(SyntaxKind.VariableDeclarator) Then Return False End If Dim declarator = DirectCast(declaration.Parent, VariableDeclaratorSyntax) Dim identifier = DirectCast(declaration, ModifiedIdentifierSyntax) Return identifier.ArrayBounds IsNot Nothing OrElse GetInitializerExpression(declarator.Initializer, declarator.AsClause) IsNot Nothing Case SyntaxKind.PropertyStatement Dim propertyStatement = DirectCast(declaration, PropertyStatementSyntax) Return GetInitializerExpression(propertyStatement.Initializer, propertyStatement.AsClause) IsNot Nothing Case Else Return False End Select End Function Friend Overrides Function IsRecordPrimaryConstructorParameter(declaration As SyntaxNode) As Boolean Return False End Function Friend Overrides Function IsPropertyAccessorDeclarationMatchingPrimaryConstructorParameter(declaration As SyntaxNode, newContainingType As INamedTypeSymbol, ByRef isFirstAccessor As Boolean) As Boolean Return False End Function Private Shared Function GetInitializerExpression(equalsValue As EqualsValueSyntax, asClause As AsClauseSyntax) As ExpressionSyntax If equalsValue IsNot Nothing Then Return equalsValue.Value End If If asClause IsNot Nothing AndAlso asClause.IsKind(SyntaxKind.AsNewClause) Then Return DirectCast(asClause, AsNewClauseSyntax).NewExpression End If Return Nothing End Function ''' <summary> ''' VB symbols return references that represent the declaration statement. ''' The node that represenets the whole declaration (the block) is the parent node if it exists. ''' For example, a method with a body is represented by a SubBlock/FunctionBlock while a method without a body ''' is represented by its declaration statement. ''' </summary> Protected Overrides Function GetSymbolDeclarationSyntax(reference As SyntaxReference, cancellationToken As CancellationToken) As SyntaxNode Dim syntax = reference.GetSyntax(cancellationToken) Dim parent = syntax.Parent Select Case syntax.Kind ' declarations that always have block Case SyntaxKind.NamespaceStatement Debug.Assert(parent.Kind = SyntaxKind.NamespaceBlock) Return parent Case SyntaxKind.ClassStatement Debug.Assert(parent.Kind = SyntaxKind.ClassBlock) Return parent Case SyntaxKind.StructureStatement Debug.Assert(parent.Kind = SyntaxKind.StructureBlock) Return parent Case SyntaxKind.InterfaceStatement Debug.Assert(parent.Kind = SyntaxKind.InterfaceBlock) Return parent Case SyntaxKind.ModuleStatement Debug.Assert(parent.Kind = SyntaxKind.ModuleBlock) Return parent Case SyntaxKind.EnumStatement Debug.Assert(parent.Kind = SyntaxKind.EnumBlock) Return parent Case SyntaxKind.SubNewStatement Debug.Assert(parent.Kind = SyntaxKind.ConstructorBlock) Return parent Case SyntaxKind.OperatorStatement Debug.Assert(parent.Kind = SyntaxKind.OperatorBlock) Return parent Case SyntaxKind.GetAccessorStatement Debug.Assert(parent.Kind = SyntaxKind.GetAccessorBlock) Return parent Case SyntaxKind.SetAccessorStatement Debug.Assert(parent.Kind = SyntaxKind.SetAccessorBlock) Return parent Case SyntaxKind.AddHandlerAccessorStatement Debug.Assert(parent.Kind = SyntaxKind.AddHandlerAccessorBlock) Return parent Case SyntaxKind.RemoveHandlerAccessorStatement Debug.Assert(parent.Kind = SyntaxKind.RemoveHandlerAccessorBlock) Return parent Case SyntaxKind.RaiseEventAccessorStatement Debug.Assert(parent.Kind = SyntaxKind.RaiseEventAccessorBlock) Return parent ' declarations that may or may not have block Case SyntaxKind.SubStatement Return If(parent.Kind = SyntaxKind.SubBlock, parent, syntax) Case SyntaxKind.FunctionStatement Return If(parent.Kind = SyntaxKind.FunctionBlock, parent, syntax) Case SyntaxKind.PropertyStatement Return If(parent.Kind = SyntaxKind.PropertyBlock, parent, syntax) Case SyntaxKind.EventStatement Return If(parent.Kind = SyntaxKind.EventBlock, parent, syntax) ' declarations that never have a block Case SyntaxKind.ModifiedIdentifier Contract.ThrowIfFalse(parent.Parent.IsKind(SyntaxKind.FieldDeclaration)) Dim variableDeclaration = CType(parent, VariableDeclaratorSyntax) Return If(variableDeclaration.Names.Count = 1, parent, syntax) Case SyntaxKind.VariableDeclarator ' fields are represented by ModifiedIdentifier: Throw ExceptionUtilities.UnexpectedValue(syntax.Kind) Case Else Return syntax End Select End Function Friend Overrides Function IsConstructorWithMemberInitializers(declaration As SyntaxNode) As Boolean Dim ctor = TryCast(declaration, ConstructorBlockSyntax) If ctor Is Nothing Then Return False End If ' Constructor includes field initializers if the first statement ' isn't a call to another constructor of the declaring class or module. If ctor.Statements.Count = 0 Then Return True End If Dim firstStatement = ctor.Statements.First If Not firstStatement.IsKind(SyntaxKind.ExpressionStatement) Then Return True End If Dim expressionStatement = DirectCast(firstStatement, ExpressionStatementSyntax) If Not expressionStatement.Expression.IsKind(SyntaxKind.InvocationExpression) Then Return True End If Dim invocation = DirectCast(expressionStatement.Expression, InvocationExpressionSyntax) If Not invocation.Expression.IsKind(SyntaxKind.SimpleMemberAccessExpression) Then Return True End If Dim memberAccess = DirectCast(invocation.Expression, MemberAccessExpressionSyntax) If Not memberAccess.Name.IsKind(SyntaxKind.IdentifierName) OrElse Not memberAccess.Name.Identifier.IsKind(SyntaxKind.IdentifierToken) Then Return True End If ' Note that ValueText returns "New" for both New and [New] If Not String.Equals(memberAccess.Name.Identifier.ToString(), "New", StringComparison.OrdinalIgnoreCase) Then Return True End If Return memberAccess.Expression.IsKind(SyntaxKind.MyBaseKeyword) End Function Friend Overrides Function IsPartial(type As INamedTypeSymbol) As Boolean Dim syntaxRefs = type.DeclaringSyntaxReferences Return syntaxRefs.Length > 1 OrElse DirectCast(syntaxRefs.Single().GetSyntax(), TypeStatementSyntax).Modifiers.Any(SyntaxKind.PartialKeyword) End Function Protected Overrides Function GetSymbolEdits( editKind As EditKind, oldNode As SyntaxNode, newNode As SyntaxNode, oldModel As SemanticModel, newModel As SemanticModel, editMap As IReadOnlyDictionary(Of SyntaxNode, EditKind), cancellationToken As CancellationToken) As OneOrMany(Of (oldSymbol As ISymbol, newSymbol As ISymbol, editKind As EditKind)) Dim oldSymbols As OneOrMany(Of ISymbol) = Nothing Dim newSymbols As OneOrMany(Of ISymbol) = Nothing If editKind = EditKind.Delete Then If Not TryGetSyntaxNodesForEdit(editKind, oldNode, oldModel, oldSymbols, cancellationToken) Then Return OneOrMany(Of (ISymbol, ISymbol, EditKind)).Empty End If Return oldSymbols.Select(Function(s) New ValueTuple(Of ISymbol, ISymbol, EditKind)(s, Nothing, editKind)) End If If editKind = EditKind.Insert Then If Not TryGetSyntaxNodesForEdit(editKind, newNode, newModel, newSymbols, cancellationToken) Then Return OneOrMany(Of (ISymbol, ISymbol, EditKind)).Empty End If Return newSymbols.Select(Function(s) New ValueTuple(Of ISymbol, ISymbol, EditKind)(Nothing, s, editKind)) End If If editKind = EditKind.Update Then If Not TryGetSyntaxNodesForEdit(editKind, oldNode, oldModel, oldSymbols, cancellationToken) OrElse Not TryGetSyntaxNodesForEdit(editKind, newNode, newModel, newSymbols, cancellationToken) Then Return OneOrMany(Of (ISymbol, ISymbol, EditKind)).Empty End If If oldSymbols.Count = 1 AndAlso newSymbols.Count = 1 Then Return OneOrMany.Create((oldSymbols(0), newSymbols(0), editKind)) End If ' This only occurs when field identifiers are deleted/inserted/reordered from/to/within their variable declarator list, ' or their shared initializer is updated. The particular inserted and deleted fields will be represented by separate edits, ' but the AsNew clause of the declarator may have been updated as well, which needs to update the remaining (matching) fields. Dim builder = ArrayBuilder(Of (ISymbol, ISymbol, EditKind)).GetInstance() For Each oldSymbol In oldSymbols Dim newSymbol = newSymbols.FirstOrDefault(Function(s, o) CaseInsensitiveComparison.Equals(s.Name, o.Name), oldSymbol) If newSymbol IsNot Nothing Then builder.Add((oldSymbol, newSymbol, editKind)) End If Next Return OneOrMany.Create(builder.ToImmutableAndFree()) End If Throw ExceptionUtilities.UnexpectedValue(editKind) End Function Private Shared Function TryGetSyntaxNodesForEdit( editKind As EditKind, node As SyntaxNode, model As SemanticModel, <Out> ByRef symbols As OneOrMany(Of ISymbol), cancellationToken As CancellationToken) As Boolean Select Case node.Kind() Case SyntaxKind.ImportsStatement, SyntaxKind.NamespaceStatement, SyntaxKind.NamespaceBlock Return False Case SyntaxKind.VariableDeclarator Dim variableDeclarator = CType(node, VariableDeclaratorSyntax) If variableDeclarator.Names.Count > 1 Then symbols = OneOrMany.Create(variableDeclarator.Names.SelectAsArray(Function(n) model.GetDeclaredSymbol(n, cancellationToken))) Return True End If node = variableDeclarator.Names(0) Case SyntaxKind.FieldDeclaration If editKind = EditKind.Update Then Dim field = CType(node, FieldDeclarationSyntax) If field.Declarators.Count = 1 AndAlso field.Declarators(0).Names.Count = 1 Then node = field.Declarators(0).Names(0) Else symbols = OneOrMany.Create( (From declarator In field.Declarators From name In declarator.Names Select model.GetDeclaredSymbol(name, cancellationToken)).ToImmutableArray()) Return True End If End If End Select Dim symbol = model.GetDeclaredSymbol(node, cancellationToken) If symbol Is Nothing Then Return False End If ' Ignore partial method definition parts. ' Partial method that does not have implementation part is not emitted to metadata. ' Partial method without a definition part is a compilation error. If symbol.Kind = SymbolKind.Method AndAlso CType(symbol, IMethodSymbol).IsPartialDefinition Then Return False End If symbols = OneOrMany.Create(symbol) Return True End Function Friend Overrides Function ContainsLambda(declaration As SyntaxNode) As Boolean Return declaration.DescendantNodes().Any(AddressOf LambdaUtilities.IsLambda) End Function Friend Overrides Function IsLambda(node As SyntaxNode) As Boolean Return LambdaUtilities.IsLambda(node) End Function Friend Overrides Function IsNestedFunction(node As SyntaxNode) As Boolean Return TypeOf node Is LambdaExpressionSyntax End Function Friend Overrides Function IsLocalFunction(node As SyntaxNode) As Boolean Return False End Function Friend Overrides Function TryGetLambdaBodies(node As SyntaxNode, ByRef body1 As SyntaxNode, ByRef body2 As SyntaxNode) As Boolean Return LambdaUtilities.TryGetLambdaBodies(node, body1, body2) End Function Friend Overrides Function GetLambda(lambdaBody As SyntaxNode) As SyntaxNode Return LambdaUtilities.GetLambda(lambdaBody) End Function Protected Overrides Function GetLambdaBodyExpressionsAndStatements(lambdaBody As SyntaxNode) As IEnumerable(Of SyntaxNode) Return LambdaUtilities.GetLambdaBodyExpressionsAndStatements(lambdaBody) End Function Friend Overrides Function GetLambdaExpressionSymbol(model As SemanticModel, lambdaExpression As SyntaxNode, cancellationToken As CancellationToken) As IMethodSymbol Dim lambdaExpressionSyntax = DirectCast(lambdaExpression, LambdaExpressionSyntax) ' The semantic model only returns the lambda symbol for positions that are within the body of the lambda (not the header) Return DirectCast(model.GetEnclosingSymbol(lambdaExpressionSyntax.SubOrFunctionHeader.Span.End, cancellationToken), IMethodSymbol) End Function Friend Overrides Function GetContainingQueryExpression(node As SyntaxNode) As SyntaxNode Return node.FirstAncestorOrSelf(Of QueryExpressionSyntax) End Function Friend Overrides Function QueryClauseLambdasTypeEquivalent(oldModel As SemanticModel, oldNode As SyntaxNode, newModel As SemanticModel, newNode As SyntaxNode, cancellationToken As CancellationToken) As Boolean Select Case oldNode.Kind Case SyntaxKind.AggregateClause Dim oldInfo = oldModel.GetAggregateClauseSymbolInfo(DirectCast(oldNode, AggregateClauseSyntax), cancellationToken) Dim newInfo = newModel.GetAggregateClauseSymbolInfo(DirectCast(newNode, AggregateClauseSyntax), cancellationToken) Return MemberSignaturesEquivalent(oldInfo.Select1.Symbol, newInfo.Select1.Symbol) AndAlso MemberSignaturesEquivalent(oldInfo.Select2.Symbol, newInfo.Select2.Symbol) Case SyntaxKind.CollectionRangeVariable Dim oldInfo = oldModel.GetCollectionRangeVariableSymbolInfo(DirectCast(oldNode, CollectionRangeVariableSyntax), cancellationToken) Dim newInfo = newModel.GetCollectionRangeVariableSymbolInfo(DirectCast(newNode, CollectionRangeVariableSyntax), cancellationToken) Return MemberSignaturesEquivalent(oldInfo.AsClauseConversion.Symbol, newInfo.AsClauseConversion.Symbol) AndAlso MemberSignaturesEquivalent(oldInfo.SelectMany.Symbol, newInfo.SelectMany.Symbol) AndAlso MemberSignaturesEquivalent(oldInfo.ToQueryableCollectionConversion.Symbol, newInfo.ToQueryableCollectionConversion.Symbol) Case SyntaxKind.FunctionAggregation Dim oldInfo = oldModel.GetSymbolInfo(DirectCast(oldNode, FunctionAggregationSyntax), cancellationToken) Dim newInfo = newModel.GetSymbolInfo(DirectCast(newNode, FunctionAggregationSyntax), cancellationToken) Return MemberSignaturesEquivalent(oldInfo.Symbol, newInfo.Symbol) Case SyntaxKind.ExpressionRangeVariable Dim oldInfo = oldModel.GetSymbolInfo(DirectCast(oldNode, ExpressionRangeVariableSyntax), cancellationToken) Dim newInfo = newModel.GetSymbolInfo(DirectCast(newNode, ExpressionRangeVariableSyntax), cancellationToken) Return MemberSignaturesEquivalent(oldInfo.Symbol, newInfo.Symbol) Case SyntaxKind.AscendingOrdering, SyntaxKind.DescendingOrdering Dim oldInfo = oldModel.GetSymbolInfo(DirectCast(oldNode, OrderingSyntax), cancellationToken) Dim newInfo = newModel.GetSymbolInfo(DirectCast(newNode, OrderingSyntax), cancellationToken) Return MemberSignaturesEquivalent(oldInfo.Symbol, newInfo.Symbol) Case SyntaxKind.FromClause, SyntaxKind.WhereClause, SyntaxKind.SkipClause, SyntaxKind.TakeClause, SyntaxKind.SkipWhileClause, SyntaxKind.TakeWhileClause, SyntaxKind.GroupByClause, SyntaxKind.SimpleJoinClause, SyntaxKind.GroupJoinClause, SyntaxKind.SelectClause Dim oldInfo = oldModel.GetSymbolInfo(DirectCast(oldNode, QueryClauseSyntax), cancellationToken) Dim newInfo = newModel.GetSymbolInfo(DirectCast(newNode, QueryClauseSyntax), cancellationToken) Return MemberSignaturesEquivalent(oldInfo.Symbol, newInfo.Symbol) Case Else Return True End Select End Function Protected Overrides Sub ReportLocalFunctionsDeclarationRudeEdits(diagnostics As ArrayBuilder(Of RudeEditDiagnostic), bodyMatch As Match(Of SyntaxNode)) ' VB has no local functions so we don't have anything to report End Sub #End Region #Region "Diagnostic Info" Protected Overrides ReadOnly Property ErrorDisplayFormat As SymbolDisplayFormat Get Return SymbolDisplayFormat.VisualBasicShortErrorMessageFormat End Get End Property Protected Overrides Function TryGetDiagnosticSpan(node As SyntaxNode, editKind As EditKind) As TextSpan? Return TryGetDiagnosticSpanImpl(node, editKind) End Function Protected Overloads Shared Function GetDiagnosticSpan(node As SyntaxNode, editKind As EditKind) As TextSpan Return If(TryGetDiagnosticSpanImpl(node, editKind), node.Span) End Function Private Shared Function TryGetDiagnosticSpanImpl(node As SyntaxNode, editKind As EditKind) As TextSpan? Return TryGetDiagnosticSpanImpl(node.Kind, node, editKind) End Function Protected Overrides Function GetBodyDiagnosticSpan(node As SyntaxNode, editKind As EditKind) As TextSpan Return GetDiagnosticSpan(node, editKind) End Function ' internal for testing; kind is passed explicitly for testing as well Friend Shared Function TryGetDiagnosticSpanImpl(kind As SyntaxKind, node As SyntaxNode, editKind As EditKind) As TextSpan? Select Case kind Case SyntaxKind.CompilationUnit Return New TextSpan() Case SyntaxKind.OptionStatement, SyntaxKind.ImportsStatement Return node.Span Case SyntaxKind.NamespaceBlock Return GetDiagnosticSpan(DirectCast(node, NamespaceBlockSyntax).NamespaceStatement) Case SyntaxKind.NamespaceStatement Return GetDiagnosticSpan(DirectCast(node, NamespaceStatementSyntax)) Case SyntaxKind.ClassBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock, SyntaxKind.ModuleBlock Return GetDiagnosticSpan(DirectCast(node, TypeBlockSyntax).BlockStatement) Case SyntaxKind.ClassStatement, SyntaxKind.StructureStatement, SyntaxKind.InterfaceStatement, SyntaxKind.ModuleStatement Return GetDiagnosticSpan(DirectCast(node, TypeStatementSyntax)) Case SyntaxKind.EnumBlock Return TryGetDiagnosticSpanImpl(DirectCast(node, EnumBlockSyntax).EnumStatement, editKind) Case SyntaxKind.EnumStatement Dim enumStatement = DirectCast(node, EnumStatementSyntax) Return GetDiagnosticSpan(enumStatement.Modifiers, enumStatement.EnumKeyword, enumStatement.Identifier) Case SyntaxKind.SubBlock, SyntaxKind.FunctionBlock, SyntaxKind.OperatorBlock, SyntaxKind.ConstructorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.GetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock Return GetDiagnosticSpan(DirectCast(node, MethodBlockBaseSyntax).BlockStatement) Case SyntaxKind.EventBlock Return GetDiagnosticSpan(DirectCast(node, EventBlockSyntax).EventStatement) Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement, SyntaxKind.OperatorStatement, SyntaxKind.SubNewStatement, SyntaxKind.EventStatement, SyntaxKind.SetAccessorStatement, SyntaxKind.GetAccessorStatement, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorStatement, SyntaxKind.DeclareSubStatement, SyntaxKind.DeclareFunctionStatement, SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement Return GetDiagnosticSpan(DirectCast(node, MethodBaseSyntax)) Case SyntaxKind.PropertyBlock Return GetDiagnosticSpan(DirectCast(node, PropertyBlockSyntax).PropertyStatement) Case SyntaxKind.PropertyStatement Return GetDiagnosticSpan(DirectCast(node, PropertyStatementSyntax)) Case SyntaxKind.FieldDeclaration Dim fieldDeclaration = DirectCast(node, FieldDeclarationSyntax) Return GetDiagnosticSpan(fieldDeclaration.Modifiers, fieldDeclaration.Declarators.First, fieldDeclaration.Declarators.Last) Case SyntaxKind.VariableDeclarator, SyntaxKind.ModifiedIdentifier, SyntaxKind.EnumMemberDeclaration, SyntaxKind.TypeParameterSingleConstraintClause, SyntaxKind.TypeParameterMultipleConstraintClause, SyntaxKind.ClassConstraint, SyntaxKind.StructureConstraint, SyntaxKind.NewConstraint, SyntaxKind.TypeConstraint Return node.Span Case SyntaxKind.TypeParameter Return DirectCast(node, TypeParameterSyntax).Identifier.Span Case SyntaxKind.TypeParameterList, SyntaxKind.ParameterList, SyntaxKind.AttributeList, SyntaxKind.SimpleAsClause If editKind = EditKind.Delete Then Return TryGetDiagnosticSpanImpl(node.Parent, editKind) Else Return node.Span End If Case SyntaxKind.AttributesStatement, SyntaxKind.Attribute Return node.Span Case SyntaxKind.Parameter Dim parameter = DirectCast(node, ParameterSyntax) Return GetDiagnosticSpan(parameter.Modifiers, parameter.Identifier, parameter) Case SyntaxKind.MultiLineFunctionLambdaExpression, SyntaxKind.SingleLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression, SyntaxKind.SingleLineSubLambdaExpression Return GetDiagnosticSpan(DirectCast(node, LambdaExpressionSyntax).SubOrFunctionHeader) Case SyntaxKind.MultiLineIfBlock Dim ifStatement = DirectCast(node, MultiLineIfBlockSyntax).IfStatement Return GetDiagnosticSpan(ifStatement.IfKeyword, ifStatement.Condition, ifStatement.ThenKeyword) Case SyntaxKind.ElseIfBlock Dim elseIfStatement = DirectCast(node, ElseIfBlockSyntax).ElseIfStatement Return GetDiagnosticSpan(elseIfStatement.ElseIfKeyword, elseIfStatement.Condition, elseIfStatement.ThenKeyword) Case SyntaxKind.SingleLineIfStatement Dim ifStatement = DirectCast(node, SingleLineIfStatementSyntax) Return GetDiagnosticSpan(ifStatement.IfKeyword, ifStatement.Condition, ifStatement.ThenKeyword) Case SyntaxKind.SingleLineElseClause Return DirectCast(node, SingleLineElseClauseSyntax).ElseKeyword.Span Case SyntaxKind.TryBlock Return DirectCast(node, TryBlockSyntax).TryStatement.TryKeyword.Span Case SyntaxKind.CatchBlock Return DirectCast(node, CatchBlockSyntax).CatchStatement.CatchKeyword.Span Case SyntaxKind.FinallyBlock Return DirectCast(node, FinallyBlockSyntax).FinallyStatement.FinallyKeyword.Span Case SyntaxKind.SyncLockBlock Return DirectCast(node, SyncLockBlockSyntax).SyncLockStatement.Span Case SyntaxKind.WithBlock Return DirectCast(node, WithBlockSyntax).WithStatement.Span Case SyntaxKind.UsingBlock Return DirectCast(node, UsingBlockSyntax).UsingStatement.Span Case SyntaxKind.SimpleDoLoopBlock, SyntaxKind.DoWhileLoopBlock, SyntaxKind.DoUntilLoopBlock, SyntaxKind.DoLoopWhileBlock, SyntaxKind.DoLoopUntilBlock Return DirectCast(node, DoLoopBlockSyntax).DoStatement.Span Case SyntaxKind.WhileBlock Return DirectCast(node, WhileBlockSyntax).WhileStatement.Span Case SyntaxKind.ForEachBlock, SyntaxKind.ForBlock Return DirectCast(node, ForOrForEachBlockSyntax).ForOrForEachStatement.Span Case SyntaxKind.AwaitExpression Return DirectCast(node, AwaitExpressionSyntax).AwaitKeyword.Span Case SyntaxKind.AnonymousObjectCreationExpression Dim newWith = DirectCast(node, AnonymousObjectCreationExpressionSyntax) Return TextSpan.FromBounds(newWith.NewKeyword.Span.Start, newWith.Initializer.WithKeyword.Span.End) Case SyntaxKind.SingleLineFunctionLambdaExpression, SyntaxKind.SingleLineSubLambdaExpression, SyntaxKind.MultiLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression Return DirectCast(node, LambdaExpressionSyntax).SubOrFunctionHeader.Span Case SyntaxKind.QueryExpression Return TryGetDiagnosticSpanImpl(DirectCast(node, QueryExpressionSyntax).Clauses.First(), editKind) Case SyntaxKind.WhereClause Return DirectCast(node, WhereClauseSyntax).WhereKeyword.Span Case SyntaxKind.SelectClause Return DirectCast(node, SelectClauseSyntax).SelectKeyword.Span Case SyntaxKind.FromClause Return DirectCast(node, FromClauseSyntax).FromKeyword.Span Case SyntaxKind.AggregateClause Return DirectCast(node, AggregateClauseSyntax).AggregateKeyword.Span Case SyntaxKind.LetClause Return DirectCast(node, LetClauseSyntax).LetKeyword.Span Case SyntaxKind.SimpleJoinClause Return DirectCast(node, SimpleJoinClauseSyntax).JoinKeyword.Span Case SyntaxKind.GroupJoinClause Dim groupJoin = DirectCast(node, GroupJoinClauseSyntax) Return TextSpan.FromBounds(groupJoin.GroupKeyword.SpanStart, groupJoin.JoinKeyword.Span.End) Case SyntaxKind.GroupByClause Return DirectCast(node, GroupByClauseSyntax).GroupKeyword.Span Case SyntaxKind.FunctionAggregation Return node.Span Case SyntaxKind.CollectionRangeVariable, SyntaxKind.ExpressionRangeVariable Return TryGetDiagnosticSpanImpl(node.Parent, editKind) Case SyntaxKind.TakeWhileClause, SyntaxKind.SkipWhileClause Dim partition = DirectCast(node, PartitionWhileClauseSyntax) Return TextSpan.FromBounds(partition.SkipOrTakeKeyword.SpanStart, partition.WhileKeyword.Span.End) Case SyntaxKind.AscendingOrdering, SyntaxKind.DescendingOrdering Return node.Span Case SyntaxKind.JoinCondition Return DirectCast(node, JoinConditionSyntax).EqualsKeyword.Span Case Else Return node.Span End Select End Function Private Overloads Shared Function GetDiagnosticSpan(ifKeyword As SyntaxToken, condition As SyntaxNode, thenKeywordOpt As SyntaxToken) As TextSpan Return TextSpan.FromBounds(ifKeyword.Span.Start, If(thenKeywordOpt.RawKind <> 0, thenKeywordOpt.Span.End, condition.Span.End)) End Function Private Overloads Shared Function GetDiagnosticSpan(node As NamespaceStatementSyntax) As TextSpan Return TextSpan.FromBounds(node.NamespaceKeyword.SpanStart, node.Name.Span.End) End Function Private Overloads Shared Function GetDiagnosticSpan(node As TypeStatementSyntax) As TextSpan Return GetDiagnosticSpan(node.Modifiers, node.DeclarationKeyword, If(node.TypeParameterList, CType(node.Identifier, SyntaxNodeOrToken))) End Function Private Overloads Shared Function GetDiagnosticSpan(modifiers As SyntaxTokenList, start As SyntaxNodeOrToken, endNode As SyntaxNodeOrToken) As TextSpan Return TextSpan.FromBounds(If(modifiers.Count <> 0, modifiers.First.SpanStart, start.SpanStart), endNode.Span.End) End Function Private Overloads Shared Function GetDiagnosticSpan(header As MethodBaseSyntax) As TextSpan Dim startToken As SyntaxToken Dim endToken As SyntaxToken If header.Modifiers.Count > 0 Then startToken = header.Modifiers.First Else Select Case header.Kind Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement startToken = DirectCast(header, DelegateStatementSyntax).DelegateKeyword Case SyntaxKind.DeclareSubStatement, SyntaxKind.DeclareFunctionStatement startToken = DirectCast(header, DeclareStatementSyntax).DeclareKeyword Case Else startToken = header.DeclarationKeyword End Select End If If header.ParameterList IsNot Nothing Then endToken = header.ParameterList.CloseParenToken Else Select Case header.Kind Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement endToken = DirectCast(header, MethodStatementSyntax).Identifier Case SyntaxKind.DeclareSubStatement, SyntaxKind.DeclareFunctionStatement endToken = DirectCast(header, DeclareStatementSyntax).LibraryName.Token Case SyntaxKind.OperatorStatement endToken = DirectCast(header, OperatorStatementSyntax).OperatorToken Case SyntaxKind.SubNewStatement endToken = DirectCast(header, SubNewStatementSyntax).NewKeyword Case SyntaxKind.PropertyStatement endToken = DirectCast(header, PropertyStatementSyntax).Identifier Case SyntaxKind.EventStatement endToken = DirectCast(header, EventStatementSyntax).Identifier Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement endToken = DirectCast(header, DelegateStatementSyntax).Identifier Case SyntaxKind.SetAccessorStatement, SyntaxKind.GetAccessorStatement, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorStatement endToken = header.DeclarationKeyword Case Else Throw ExceptionUtilities.UnexpectedValue(header.Kind) End Select End If Return TextSpan.FromBounds(startToken.SpanStart, endToken.Span.End) End Function Private Overloads Shared Function GetDiagnosticSpan(lambda As LambdaHeaderSyntax) As TextSpan Dim startToken = If(lambda.Modifiers.Count <> 0, lambda.Modifiers.First, lambda.DeclarationKeyword) Dim endToken As SyntaxToken If lambda.ParameterList IsNot Nothing Then endToken = lambda.ParameterList.CloseParenToken Else endToken = lambda.DeclarationKeyword End If Return TextSpan.FromBounds(startToken.SpanStart, endToken.Span.End) End Function Friend Overrides Function GetLambdaParameterDiagnosticSpan(lambda As SyntaxNode, ordinal As Integer) As TextSpan Select Case lambda.Kind Case SyntaxKind.MultiLineFunctionLambdaExpression, SyntaxKind.SingleLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression, SyntaxKind.SingleLineSubLambdaExpression Return DirectCast(lambda, LambdaExpressionSyntax).SubOrFunctionHeader.ParameterList.Parameters(ordinal).Identifier.Span Case Else Return lambda.Span End Select End Function Friend Overrides Function GetDisplayName(symbol As INamedTypeSymbol) As String Select Case symbol.TypeKind Case TypeKind.Structure Return VBFeaturesResources.structure_ Case TypeKind.Module Return VBFeaturesResources.module_ Case Else Return MyBase.GetDisplayName(symbol) End Select End Function Friend Overrides Function GetDisplayName(symbol As IMethodSymbol) As String Select Case symbol.MethodKind Case MethodKind.StaticConstructor Return VBFeaturesResources.Shared_constructor Case Else Return MyBase.GetDisplayName(symbol) End Select End Function Friend Overrides Function GetDisplayName(symbol As IPropertySymbol) As String If symbol.IsWithEvents Then Return VBFeaturesResources.WithEvents_field End If Return MyBase.GetDisplayName(symbol) End Function Protected Overrides Function TryGetDisplayName(node As SyntaxNode, editKind As EditKind) As String Return TryGetDisplayNameImpl(node, editKind) End Function Protected Overloads Shared Function GetDisplayName(node As SyntaxNode, editKind As EditKind) As String Dim result = TryGetDisplayNameImpl(node, editKind) If result Is Nothing Then Throw ExceptionUtilities.UnexpectedValue(node.Kind) End If Return result End Function Protected Overrides Function GetBodyDisplayName(node As SyntaxNode, Optional editKind As EditKind = EditKind.Update) As String Return GetDisplayName(node, editKind) End Function Private Shared Function TryGetDisplayNameImpl(node As SyntaxNode, editKind As EditKind) As String Select Case node.Kind ' top-level Case SyntaxKind.OptionStatement Return VBFeaturesResources.option_ Case SyntaxKind.ImportsStatement Return VBFeaturesResources.import Case SyntaxKind.NamespaceBlock, SyntaxKind.NamespaceStatement Return FeaturesResources.namespace_ Case SyntaxKind.ClassBlock, SyntaxKind.ClassStatement Return FeaturesResources.class_ Case SyntaxKind.StructureBlock, SyntaxKind.StructureStatement Return VBFeaturesResources.structure_ Case SyntaxKind.InterfaceBlock, SyntaxKind.InterfaceStatement Return FeaturesResources.interface_ Case SyntaxKind.ModuleBlock, SyntaxKind.ModuleStatement Return VBFeaturesResources.module_ Case SyntaxKind.EnumBlock, SyntaxKind.EnumStatement Return FeaturesResources.enum_ Case SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement Return FeaturesResources.delegate_ Case SyntaxKind.FieldDeclaration Dim declaration = DirectCast(node, FieldDeclarationSyntax) Return If(declaration.Modifiers.Any(SyntaxKind.WithEventsKeyword), VBFeaturesResources.WithEvents_field, If(declaration.Modifiers.Any(SyntaxKind.ConstKeyword), FeaturesResources.const_field, FeaturesResources.field)) Case SyntaxKind.VariableDeclarator, SyntaxKind.ModifiedIdentifier Return TryGetDisplayNameImpl(node.Parent, editKind) Case SyntaxKind.SubBlock, SyntaxKind.FunctionBlock, SyntaxKind.SubStatement, SyntaxKind.FunctionStatement, SyntaxKind.DeclareSubStatement, SyntaxKind.DeclareFunctionStatement Return FeaturesResources.method Case SyntaxKind.OperatorBlock, SyntaxKind.OperatorStatement Return FeaturesResources.operator_ Case SyntaxKind.ConstructorBlock Return If(CType(node, ConstructorBlockSyntax).SubNewStatement.Modifiers.Any(SyntaxKind.SharedKeyword), VBFeaturesResources.Shared_constructor, FeaturesResources.constructor) Case SyntaxKind.SubNewStatement Return If(CType(node, SubNewStatementSyntax).Modifiers.Any(SyntaxKind.SharedKeyword), VBFeaturesResources.Shared_constructor, FeaturesResources.constructor) Case SyntaxKind.PropertyBlock Return FeaturesResources.property_ Case SyntaxKind.PropertyStatement Return If(node.IsParentKind(SyntaxKind.PropertyBlock), FeaturesResources.property_, FeaturesResources.auto_property) Case SyntaxKind.EventBlock, SyntaxKind.EventStatement Return FeaturesResources.event_ Case SyntaxKind.EnumMemberDeclaration Return FeaturesResources.enum_value Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorStatement Return FeaturesResources.property_accessor Case SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorStatement Return FeaturesResources.event_accessor Case SyntaxKind.TypeParameterSingleConstraintClause, SyntaxKind.TypeParameterMultipleConstraintClause, SyntaxKind.ClassConstraint, SyntaxKind.StructureConstraint, SyntaxKind.NewConstraint, SyntaxKind.TypeConstraint Return FeaturesResources.type_constraint Case SyntaxKind.SimpleAsClause Return VBFeaturesResources.as_clause Case SyntaxKind.TypeParameterList Return VBFeaturesResources.type_parameters Case SyntaxKind.TypeParameter Return FeaturesResources.type_parameter Case SyntaxKind.ParameterList Return VBFeaturesResources.parameters Case SyntaxKind.Parameter Return FeaturesResources.parameter Case SyntaxKind.AttributeList, SyntaxKind.AttributesStatement Return VBFeaturesResources.attributes Case SyntaxKind.Attribute Return FeaturesResources.attribute ' statement-level Case SyntaxKind.TryBlock Return VBFeaturesResources.Try_block Case SyntaxKind.CatchBlock Return VBFeaturesResources.Catch_clause Case SyntaxKind.FinallyBlock Return VBFeaturesResources.Finally_clause Case SyntaxKind.UsingBlock Return If(editKind = EditKind.Update, VBFeaturesResources.Using_statement, VBFeaturesResources.Using_block) Case SyntaxKind.WithBlock Return If(editKind = EditKind.Update, VBFeaturesResources.With_statement, VBFeaturesResources.With_block) Case SyntaxKind.SyncLockBlock Return If(editKind = EditKind.Update, VBFeaturesResources.SyncLock_statement, VBFeaturesResources.SyncLock_block) Case SyntaxKind.ForEachBlock Return If(editKind = EditKind.Update, VBFeaturesResources.For_Each_statement, VBFeaturesResources.For_Each_block) Case SyntaxKind.OnErrorGoToMinusOneStatement, SyntaxKind.OnErrorGoToZeroStatement, SyntaxKind.OnErrorResumeNextStatement, SyntaxKind.OnErrorGoToLabelStatement Return VBFeaturesResources.On_Error_statement Case SyntaxKind.ResumeStatement, SyntaxKind.ResumeNextStatement, SyntaxKind.ResumeLabelStatement Return VBFeaturesResources.Resume_statement Case SyntaxKind.YieldStatement Return VBFeaturesResources.Yield_statement Case SyntaxKind.AwaitExpression Return VBFeaturesResources.Await_expression Case SyntaxKind.MultiLineFunctionLambdaExpression, SyntaxKind.SingleLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression, SyntaxKind.SingleLineSubLambdaExpression, SyntaxKind.FunctionLambdaHeader, SyntaxKind.SubLambdaHeader Return VBFeaturesResources.Lambda Case SyntaxKind.WhereClause Return VBFeaturesResources.Where_clause Case SyntaxKind.SelectClause Return VBFeaturesResources.Select_clause Case SyntaxKind.FromClause Return VBFeaturesResources.From_clause Case SyntaxKind.AggregateClause Return VBFeaturesResources.Aggregate_clause Case SyntaxKind.LetClause Return VBFeaturesResources.Let_clause Case SyntaxKind.SimpleJoinClause Return VBFeaturesResources.Join_clause Case SyntaxKind.GroupJoinClause Return VBFeaturesResources.Group_Join_clause Case SyntaxKind.GroupByClause Return VBFeaturesResources.Group_By_clause Case SyntaxKind.FunctionAggregation Return VBFeaturesResources.Function_aggregation Case SyntaxKind.CollectionRangeVariable, SyntaxKind.ExpressionRangeVariable Return TryGetDisplayNameImpl(node.Parent, editKind) Case SyntaxKind.TakeWhileClause Return VBFeaturesResources.Take_While_clause Case SyntaxKind.SkipWhileClause Return VBFeaturesResources.Skip_While_clause Case SyntaxKind.AscendingOrdering, SyntaxKind.DescendingOrdering Return VBFeaturesResources.Ordering_clause Case SyntaxKind.JoinCondition Return VBFeaturesResources.Join_condition Case Else Return Nothing End Select End Function #End Region #Region "Top-level Syntactic Rude Edits" Private Structure EditClassifier Private ReadOnly _analyzer As VisualBasicEditAndContinueAnalyzer Private ReadOnly _diagnostics As ArrayBuilder(Of RudeEditDiagnostic) Private ReadOnly _match As Match(Of SyntaxNode) Private ReadOnly _oldNode As SyntaxNode Private ReadOnly _newNode As SyntaxNode Private ReadOnly _kind As EditKind Private ReadOnly _span As TextSpan? Public Sub New(analyzer As VisualBasicEditAndContinueAnalyzer, diagnostics As ArrayBuilder(Of RudeEditDiagnostic), oldNode As SyntaxNode, newNode As SyntaxNode, kind As EditKind, Optional match As Match(Of SyntaxNode) = Nothing, Optional span As TextSpan? = Nothing) _analyzer = analyzer _diagnostics = diagnostics _oldNode = oldNode _newNode = newNode _kind = kind _span = span _match = match End Sub Private Sub ReportError(kind As RudeEditKind) ReportError(kind, {GetDisplayName(If(_newNode, _oldNode), EditKind.Update)}) End Sub Private Sub ReportError(kind As RudeEditKind, args As String()) _diagnostics.Add(New RudeEditDiagnostic(kind, GetSpan(), If(_newNode, _oldNode), args)) End Sub Private Sub ReportError(kind As RudeEditKind, spanNode As SyntaxNode, displayNode As SyntaxNode) _diagnostics.Add(New RudeEditDiagnostic(kind, GetDiagnosticSpan(spanNode, _kind), displayNode, {GetDisplayName(displayNode, EditKind.Update)})) End Sub Private Function GetSpan() As TextSpan If _span.HasValue Then Return _span.Value End If If _newNode Is Nothing Then Return _analyzer.GetDeletedNodeDiagnosticSpan(_match.Matches, _oldNode) Else Return GetDiagnosticSpan(_newNode, _kind) End If End Function Public Sub ClassifyEdit() Select Case _kind Case EditKind.Delete ClassifyDelete(_oldNode) Return Case EditKind.Update ClassifyUpdate(_oldNode, _newNode) Return Case EditKind.Move ClassifyMove(_newNode) Return Case EditKind.Insert ClassifyInsert(_newNode) Return Case EditKind.Reorder ClassifyReorder(_oldNode, _newNode) Return Case Else Throw ExceptionUtilities.UnexpectedValue(_kind) End Select End Sub #Region "Move and Reorder" Private Sub ClassifyMove(newNode As SyntaxNode) Select Case newNode.Kind Case SyntaxKind.ModifiedIdentifier, SyntaxKind.VariableDeclarator ' Identifier can be moved within the same type declaration. ' Determine validity of such change in semantic analysis. Return Case Else ReportError(RudeEditKind.Move) End Select End Sub Private Sub ClassifyReorder(oldNode As SyntaxNode, newNode As SyntaxNode) Select Case newNode.Kind Case SyntaxKind.OptionStatement, SyntaxKind.ImportsStatement, SyntaxKind.AttributesStatement, SyntaxKind.NamespaceBlock, SyntaxKind.ClassBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock, SyntaxKind.ModuleBlock, SyntaxKind.EnumBlock, SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement, SyntaxKind.SubBlock, SyntaxKind.FunctionBlock, SyntaxKind.DeclareSubStatement, SyntaxKind.DeclareFunctionStatement, SyntaxKind.ConstructorBlock, SyntaxKind.OperatorBlock, SyntaxKind.PropertyBlock, SyntaxKind.EventBlock, SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock, SyntaxKind.ClassConstraint, SyntaxKind.StructureConstraint, SyntaxKind.NewConstraint, SyntaxKind.TypeConstraint, SyntaxKind.AttributeList, SyntaxKind.Attribute ' We'll ignore these edits. A general policy is to ignore edits that are only discoverable via reflection. Return Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement ' Interface methods. We could allow reordering of non-COM interface methods. Debug.Assert(oldNode.Parent.IsKind(SyntaxKind.InterfaceBlock) AndAlso newNode.Parent.IsKind(SyntaxKind.InterfaceBlock)) ReportError(RudeEditKind.Move) Return Case SyntaxKind.PropertyStatement, SyntaxKind.FieldDeclaration, SyntaxKind.EventStatement ' Maybe we could allow changing order of field declarations unless the containing type layout is sequential, ' and it's not a COM interface. ReportError(RudeEditKind.Move) Return Case SyntaxKind.EnumMemberDeclaration ' To allow this change we would need to check that values of all fields of the enum ' are preserved, or make sure we can update all method bodies that accessed those that changed. ReportError(RudeEditKind.Move) Return Case SyntaxKind.TypeParameter, SyntaxKind.Parameter ReportError(RudeEditKind.Move) Return Case SyntaxKind.ModifiedIdentifier, SyntaxKind.VariableDeclarator ' Identifier can be moved within the same type declaration. ' Determine validity of such change in semantic analysis. Return Case Else Throw ExceptionUtilities.UnexpectedValue(newNode.Kind) End Select End Sub #End Region #Region "Insert" Private Sub ClassifyInsert(node As SyntaxNode) Select Case node.Kind Case SyntaxKind.OptionStatement, SyntaxKind.NamespaceBlock ReportError(RudeEditKind.Insert) Return Case SyntaxKind.AttributesStatement ' Module/assembly attribute ReportError(RudeEditKind.Insert) Return Case SyntaxKind.Attribute ' Only module/assembly attributes are rude If node.Parent.IsParentKind(SyntaxKind.AttributesStatement) Then ReportError(RudeEditKind.Insert) End If Return Case SyntaxKind.AttributeList ' Only module/assembly attributes are rude If node.IsParentKind(SyntaxKind.AttributesStatement) Then ReportError(RudeEditKind.Insert) End If Return End Select End Sub #End Region #Region "Delete" Private Sub ClassifyDelete(oldNode As SyntaxNode) Select Case oldNode.Kind Case SyntaxKind.OptionStatement, SyntaxKind.NamespaceBlock, SyntaxKind.AttributesStatement ReportError(RudeEditKind.Delete) Return Case SyntaxKind.AttributeList ' Only module/assembly attributes are rude edits If oldNode.IsParentKind(SyntaxKind.AttributesStatement) Then ReportError(RudeEditKind.Insert) End If Return Case SyntaxKind.Attribute ' Only module/assembly attributes are rude edits If oldNode.Parent.IsParentKind(SyntaxKind.AttributesStatement) Then ReportError(RudeEditKind.Insert) End If Return End Select End Sub #End Region #Region "Update" Private Sub ClassifyUpdate(oldNode As SyntaxNode, newNode As SyntaxNode) Select Case newNode.Kind Case SyntaxKind.OptionStatement ReportError(RudeEditKind.Update) Return Case SyntaxKind.NamespaceStatement ClassifyUpdate(DirectCast(oldNode, NamespaceStatementSyntax), DirectCast(newNode, NamespaceStatementSyntax)) Return Case SyntaxKind.AttributesStatement ReportError(RudeEditKind.Update) Return Case SyntaxKind.Attribute ' Only module/assembly attributes are rude edits If newNode.Parent.IsParentKind(SyntaxKind.AttributesStatement) Then ReportError(RudeEditKind.Update) End If Return End Select End Sub Private Sub ClassifyUpdate(oldNode As NamespaceStatementSyntax, newNode As NamespaceStatementSyntax) Debug.Assert(Not SyntaxFactory.AreEquivalent(oldNode.Name, newNode.Name)) ReportError(RudeEditKind.Renamed) End Sub Public Sub ClassifyDeclarationBodyRudeUpdates(newDeclarationOrBody As SyntaxNode) For Each node In newDeclarationOrBody.DescendantNodesAndSelf() Select Case node.Kind Case SyntaxKind.AggregateClause, SyntaxKind.GroupByClause, SyntaxKind.SimpleJoinClause, SyntaxKind.GroupJoinClause ReportError(RudeEditKind.ComplexQueryExpression, node, Me._newNode) Return Case SyntaxKind.LocalDeclarationStatement Dim declaration = DirectCast(node, LocalDeclarationStatementSyntax) If declaration.Modifiers.Any(SyntaxKind.StaticKeyword) Then ReportError(RudeEditKind.UpdateStaticLocal) End If End Select Next End Sub #End Region End Structure Friend Overrides Sub ReportTopLevelSyntacticRudeEdits( diagnostics As ArrayBuilder(Of RudeEditDiagnostic), match As Match(Of SyntaxNode), edit As Edit(Of SyntaxNode), editMap As Dictionary(Of SyntaxNode, EditKind)) ' For most nodes we ignore Insert and Delete edits if their parent was also inserted or deleted, respectively. ' For ModifiedIdentifiers though we check the grandparent instead because variables can move across ' VariableDeclarators. Moving a variable from a VariableDeclarator that only has a single variable results in ' deletion of that declarator. We don't want to report that delete. Similarly for moving to a new VariableDeclarator. If edit.Kind = EditKind.Delete AndAlso edit.OldNode.IsKind(SyntaxKind.ModifiedIdentifier) AndAlso edit.OldNode.Parent.IsKind(SyntaxKind.VariableDeclarator) Then If HasEdit(editMap, edit.OldNode.Parent.Parent, EditKind.Delete) Then Return End If ElseIf edit.Kind = EditKind.Insert AndAlso edit.NewNode.IsKind(SyntaxKind.ModifiedIdentifier) AndAlso edit.NewNode.Parent.IsKind(SyntaxKind.VariableDeclarator) Then If HasEdit(editMap, edit.NewNode.Parent.Parent, EditKind.Insert) Then Return End If ElseIf HasParentEdit(editMap, edit) Then Return End If Dim classifier = New EditClassifier(Me, diagnostics, edit.OldNode, edit.NewNode, edit.Kind, match) classifier.ClassifyEdit() End Sub Friend Overrides Sub ReportMemberBodyUpdateRudeEdits(diagnostics As ArrayBuilder(Of RudeEditDiagnostic), newMember As SyntaxNode, span As TextSpan?) Dim classifier = New EditClassifier(Me, diagnostics, Nothing, newMember, EditKind.Update, span:=span) classifier.ClassifyDeclarationBodyRudeUpdates(newMember) End Sub #End Region #Region "Semantic Rude Edits" Protected Overrides Function AreFixedSizeBufferSizesEqual(oldField As IFieldSymbol, newField As IFieldSymbol, cancellationToken As CancellationToken) As Boolean Throw ExceptionUtilities.Unreachable End Function Protected Overrides Function AreHandledEventsEqual(oldMethod As IMethodSymbol, newMethod As IMethodSymbol) As Boolean Return oldMethod.HandledEvents.SequenceEqual( newMethod.HandledEvents, Function(x, y) Return x.HandlesKind = y.HandlesKind AndAlso SymbolsEquivalent(x.EventContainer, y.EventContainer) AndAlso SymbolsEquivalent(x.EventSymbol, y.EventSymbol) AndAlso SymbolsEquivalent(x.WithEventsSourceProperty, y.WithEventsSourceProperty) End Function) End Function Friend Overrides Sub ReportInsertedMemberSymbolRudeEdits(diagnostics As ArrayBuilder(Of RudeEditDiagnostic), newSymbol As ISymbol, newNode As SyntaxNode, insertingIntoExistingContainingType As Boolean) Dim kind = GetInsertedMemberSymbolRudeEditKind(newSymbol, insertingIntoExistingContainingType) If kind <> RudeEditKind.None Then diagnostics.Add(New RudeEditDiagnostic( kind, GetDiagnosticSpan(newNode, EditKind.Insert), newNode, arguments:={GetDisplayName(newNode, EditKind.Insert)})) End If End Sub Private Shared Function GetInsertedMemberSymbolRudeEditKind(newSymbol As ISymbol, insertingIntoExistingContainingType As Boolean) As RudeEditKind Select Case newSymbol.Kind Case SymbolKind.Method Dim method = DirectCast(newSymbol, IMethodSymbol) ' Inserting P/Invoke into a new or existing type is not allowed. If method.GetDllImportData() IsNot Nothing Then Return RudeEditKind.InsertDllImport End If ' Inserting method with handles clause into a new or existing type is not allowed. If Not method.HandledEvents.IsEmpty Then Return RudeEditKind.InsertHandlesClause End If Case SymbolKind.NamedType Dim type = CType(newSymbol, INamedTypeSymbol) ' Inserting module is not allowed. If type.TypeKind = TypeKind.Module Then Return RudeEditKind.Insert End If End Select ' All rude edits below only apply when inserting into an existing type (not when the type itself is inserted): If Not insertingIntoExistingContainingType Then Return RudeEditKind.None End If If newSymbol.ContainingType.Arity > 0 AndAlso newSymbol.Kind <> SymbolKind.NamedType Then Return RudeEditKind.InsertIntoGenericType End If ' Inserting virtual or interface member is not allowed. If (newSymbol.IsVirtual Or newSymbol.IsOverride Or newSymbol.IsAbstract) AndAlso newSymbol.Kind <> SymbolKind.NamedType Then Return RudeEditKind.InsertVirtual End If Select Case newSymbol.Kind Case SymbolKind.Method Dim method = DirectCast(newSymbol, IMethodSymbol) ' Inserting generic method into an existing type is not allowed. If method.Arity > 0 Then Return RudeEditKind.InsertGenericMethod End If ' Inserting operator to an existing type is not allowed. If method.MethodKind = MethodKind.Conversion OrElse method.MethodKind = MethodKind.UserDefinedOperator Then Return RudeEditKind.InsertOperator End If Return RudeEditKind.None Case SymbolKind.Field ' Inserting a field into an enum is not allowed. If newSymbol.ContainingType.TypeKind = TypeKind.Enum Then Return RudeEditKind.Insert End If Return RudeEditKind.None End Select Return RudeEditKind.None End Function #End Region #Region "Exception Handling Rude Edits" Protected Overrides Function GetExceptionHandlingAncestors(node As SyntaxNode, isNonLeaf As Boolean) As List(Of SyntaxNode) Dim result = New List(Of SyntaxNode)() While node IsNot Nothing Dim kind = node.Kind Select Case kind Case SyntaxKind.TryBlock If isNonLeaf Then result.Add(node) End If Case SyntaxKind.CatchBlock, SyntaxKind.FinallyBlock result.Add(node) Debug.Assert(node.Parent.Kind = SyntaxKind.TryBlock) node = node.Parent Case SyntaxKind.ClassBlock, SyntaxKind.StructureBlock ' stop at type declaration Exit While End Select ' stop at lambda If LambdaUtilities.IsLambda(node) Then Exit While End If node = node.Parent End While Return result End Function Friend Overrides Sub ReportEnclosingExceptionHandlingRudeEdits(diagnostics As ArrayBuilder(Of RudeEditDiagnostic), exceptionHandlingEdits As IEnumerable(Of Edit(Of SyntaxNode)), oldStatement As SyntaxNode, newStatementSpan As TextSpan) For Each edit In exceptionHandlingEdits Debug.Assert(edit.Kind <> EditKind.Update OrElse edit.OldNode.RawKind = edit.NewNode.RawKind) If edit.Kind <> EditKind.Update OrElse Not AreExceptionHandlingPartsEquivalent(edit.OldNode, edit.NewNode) Then AddAroundActiveStatementRudeDiagnostic(diagnostics, edit.OldNode, edit.NewNode, newStatementSpan) End If Next End Sub Private Shared Function AreExceptionHandlingPartsEquivalent(oldNode As SyntaxNode, newNode As SyntaxNode) As Boolean Select Case oldNode.Kind Case SyntaxKind.TryBlock Dim oldTryBlock = DirectCast(oldNode, TryBlockSyntax) Dim newTryBlock = DirectCast(newNode, TryBlockSyntax) Return SyntaxFactory.AreEquivalent(oldTryBlock.FinallyBlock, newTryBlock.FinallyBlock) AndAlso SyntaxFactory.AreEquivalent(oldTryBlock.CatchBlocks, newTryBlock.CatchBlocks) Case SyntaxKind.CatchBlock, SyntaxKind.FinallyBlock Return SyntaxFactory.AreEquivalent(oldNode, newNode) Case Else Throw ExceptionUtilities.UnexpectedValue(oldNode.Kind) End Select End Function ''' <summary> ''' An active statement (leaf or not) inside a "Catch" makes the Catch part readonly. ''' An active statement (leaf or not) inside a "Finally" makes the whole Try/Catch/Finally part read-only. ''' An active statement (non leaf) inside a "Try" makes the Catch/Finally part read-only. ''' </summary> Protected Overrides Function GetExceptionHandlingRegion(node As SyntaxNode, <Out> ByRef coversAllChildren As Boolean) As TextSpan Select Case node.Kind Case SyntaxKind.TryBlock Dim tryBlock = DirectCast(node, TryBlockSyntax) coversAllChildren = False If tryBlock.CatchBlocks.Count = 0 Then Debug.Assert(tryBlock.FinallyBlock IsNot Nothing) Return TextSpan.FromBounds(tryBlock.FinallyBlock.SpanStart, tryBlock.EndTryStatement.Span.End) End If Return TextSpan.FromBounds(tryBlock.CatchBlocks.First().SpanStart, tryBlock.EndTryStatement.Span.End) Case SyntaxKind.CatchBlock coversAllChildren = True Return node.Span Case SyntaxKind.FinallyBlock coversAllChildren = True Return DirectCast(node.Parent, TryBlockSyntax).Span Case Else Throw ExceptionUtilities.UnexpectedValue(node.Kind) End Select End Function #End Region #Region "State Machines" Friend Overrides Function IsStateMachineMethod(declaration As SyntaxNode) As Boolean Return SyntaxUtilities.IsAsyncMethodOrLambda(declaration) OrElse SyntaxUtilities.IsIteratorMethodOrLambda(declaration) End Function Protected Overrides Sub GetStateMachineInfo(body As SyntaxNode, ByRef suspensionPoints As ImmutableArray(Of SyntaxNode), ByRef kind As StateMachineKinds) ' In VB declaration and body are represented by the same node for both lambdas and methods (unlike C#) If SyntaxUtilities.IsAsyncMethodOrLambda(body) Then suspensionPoints = SyntaxUtilities.GetAwaitExpressions(body) kind = StateMachineKinds.Async ElseIf SyntaxUtilities.IsIteratorMethodOrLambda(body) Then suspensionPoints = SyntaxUtilities.GetYieldStatements(body) kind = StateMachineKinds.Iterator Else suspensionPoints = ImmutableArray(Of SyntaxNode).Empty kind = StateMachineKinds.None End If End Sub Friend Overrides Sub ReportStateMachineSuspensionPointRudeEdits(diagnostics As ArrayBuilder(Of RudeEditDiagnostic), oldNode As SyntaxNode, newNode As SyntaxNode) ' TODO: changes around suspension points (foreach, lock, using, etc.) If newNode.IsKind(SyntaxKind.AwaitExpression) Then Dim oldContainingStatementPart = FindContainingStatementPart(oldNode) Dim newContainingStatementPart = FindContainingStatementPart(newNode) ' If the old statement has spilled state and the new doesn't, the edit is ok. We'll just not use the spilled state. If Not SyntaxFactory.AreEquivalent(oldContainingStatementPart, newContainingStatementPart) AndAlso Not HasNoSpilledState(newNode, newContainingStatementPart) Then diagnostics.Add(New RudeEditDiagnostic(RudeEditKind.AwaitStatementUpdate, newContainingStatementPart.Span)) End If End If End Sub Private Shared Function FindContainingStatementPart(node As SyntaxNode) As SyntaxNode Dim statement = TryCast(node, StatementSyntax) While statement Is Nothing Select Case node.Parent.Kind() Case SyntaxKind.ForStatement, SyntaxKind.ForEachStatement, SyntaxKind.IfStatement, SyntaxKind.WhileStatement, SyntaxKind.SimpleDoStatement, SyntaxKind.SelectStatement, SyntaxKind.UsingStatement Return node End Select If LambdaUtilities.IsLambdaBodyStatementOrExpression(node) Then Return node End If node = node.Parent statement = TryCast(node, StatementSyntax) End While Return statement End Function Private Shared Function HasNoSpilledState(awaitExpression As SyntaxNode, containingStatementPart As SyntaxNode) As Boolean Debug.Assert(awaitExpression.IsKind(SyntaxKind.AwaitExpression)) ' There is nothing within the statement part surrounding the await expression. If containingStatementPart Is awaitExpression Then Return True End If Select Case containingStatementPart.Kind() Case SyntaxKind.ExpressionStatement, SyntaxKind.ReturnStatement Dim expression = GetExpressionFromStatementPart(containingStatementPart) ' Await <expr> ' Return Await <expr> If expression Is awaitExpression Then Return True End If ' <ident> = Await <expr> ' Return <ident> = Await <expr> Return IsSimpleAwaitAssignment(expression, awaitExpression) Case SyntaxKind.VariableDeclarator ' <ident> = Await <expr> in using, for, etc ' EqualsValue -> VariableDeclarator Return awaitExpression.Parent.Parent Is containingStatementPart Case SyntaxKind.LoopUntilStatement, SyntaxKind.LoopWhileStatement, SyntaxKind.DoUntilStatement, SyntaxKind.DoWhileStatement ' Until Await <expr> ' UntilClause -> LoopUntilStatement Return awaitExpression.Parent.Parent Is containingStatementPart Case SyntaxKind.LocalDeclarationStatement ' Dim <ident> = Await <expr> ' EqualsValue -> VariableDeclarator -> LocalDeclarationStatement Return awaitExpression.Parent.Parent.Parent Is containingStatementPart End Select Return IsSimpleAwaitAssignment(containingStatementPart, awaitExpression) End Function Private Shared Function GetExpressionFromStatementPart(statement As SyntaxNode) As ExpressionSyntax Select Case statement.Kind() Case SyntaxKind.ExpressionStatement Return DirectCast(statement, ExpressionStatementSyntax).Expression Case SyntaxKind.ReturnStatement Return DirectCast(statement, ReturnStatementSyntax).Expression Case Else Throw ExceptionUtilities.UnexpectedValue(statement.Kind()) End Select End Function Private Shared Function IsSimpleAwaitAssignment(node As SyntaxNode, awaitExpression As SyntaxNode) As Boolean If node.IsKind(SyntaxKind.SimpleAssignmentStatement) Then Dim assignment = DirectCast(node, AssignmentStatementSyntax) Return assignment.Left.IsKind(SyntaxKind.IdentifierName) AndAlso assignment.Right Is awaitExpression End If Return False End Function #End Region #Region "Rude Edits around Active Statement" Friend Overrides Sub ReportOtherRudeEditsAroundActiveStatement(diagnostics As ArrayBuilder(Of RudeEditDiagnostic), match As Match(Of SyntaxNode), oldActiveStatement As SyntaxNode, newActiveStatement As SyntaxNode, isNonLeaf As Boolean) Dim onErrorOrResumeStatement = FindOnErrorOrResumeStatement(match.NewRoot) If onErrorOrResumeStatement IsNot Nothing Then AddAroundActiveStatementRudeDiagnostic(diagnostics, oldActiveStatement, onErrorOrResumeStatement, newActiveStatement.Span) End If ReportRudeEditsForAncestorsDeclaringInterStatementTemps(diagnostics, match, oldActiveStatement, newActiveStatement) End Sub Private Shared Function FindOnErrorOrResumeStatement(newDeclarationOrBody As SyntaxNode) As SyntaxNode For Each node In newDeclarationOrBody.DescendantNodes(AddressOf ChildrenCompiledInBody) Select Case node.Kind Case SyntaxKind.OnErrorGoToLabelStatement, SyntaxKind.OnErrorGoToMinusOneStatement, SyntaxKind.OnErrorGoToZeroStatement, SyntaxKind.OnErrorResumeNextStatement, SyntaxKind.ResumeStatement, SyntaxKind.ResumeNextStatement, SyntaxKind.ResumeLabelStatement Return node End Select Next Return Nothing End Function Private Sub ReportRudeEditsForAncestorsDeclaringInterStatementTemps(diagnostics As ArrayBuilder(Of RudeEditDiagnostic), match As Match(Of SyntaxNode), oldActiveStatement As SyntaxNode, newActiveStatement As SyntaxNode) ' Rude Edits for Using/SyncLock/With/ForEach statements that are added/updated around an active statement. ' Although such changes are technically possible, they might lead to confusion since ' the temporary variables these statements generate won't be properly initialized. ' ' We use a simple algorithm to match each New node with its old counterpart. ' If all nodes match this algorithm Is linear, otherwise it's quadratic. ' ' Unlike exception regions matching where we use LCS, we allow reordering of the statements. ReportUnmatchedStatements(Of SyncLockBlockSyntax)(diagnostics, match, Function(node) node.IsKind(SyntaxKind.SyncLockBlock), oldActiveStatement, newActiveStatement, areEquivalent:=Function(n1, n2) AreEquivalentIgnoringLambdaBodies(n1.SyncLockStatement.Expression, n2.SyncLockStatement.Expression), areSimilar:=Nothing) ReportUnmatchedStatements(Of WithBlockSyntax)(diagnostics, match, Function(node) node.IsKind(SyntaxKind.WithBlock), oldActiveStatement, newActiveStatement, areEquivalent:=Function(n1, n2) AreEquivalentIgnoringLambdaBodies(n1.WithStatement.Expression, n2.WithStatement.Expression), areSimilar:=Nothing) ReportUnmatchedStatements(Of UsingBlockSyntax)(diagnostics, match, Function(node) node.IsKind(SyntaxKind.UsingBlock), oldActiveStatement, newActiveStatement, areEquivalent:=Function(n1, n2) AreEquivalentIgnoringLambdaBodies(n1.UsingStatement.Expression, n2.UsingStatement.Expression), areSimilar:=Nothing) ReportUnmatchedStatements(Of ForOrForEachBlockSyntax)(diagnostics, match, Function(node) node.IsKind(SyntaxKind.ForEachBlock), oldActiveStatement, newActiveStatement, areEquivalent:=Function(n1, n2) AreEquivalentIgnoringLambdaBodies(n1.ForOrForEachStatement, n2.ForOrForEachStatement), areSimilar:=Function(n1, n2) AreEquivalentIgnoringLambdaBodies(DirectCast(n1.ForOrForEachStatement, ForEachStatementSyntax).ControlVariable, DirectCast(n2.ForOrForEachStatement, ForEachStatementSyntax).ControlVariable)) End Sub #End Region End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.Differencing Imports Microsoft.CodeAnalysis.EditAndContinue Imports Microsoft.CodeAnalysis.Host Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.EditAndContinue Friend NotInheritable Class VisualBasicEditAndContinueAnalyzer Inherits AbstractEditAndContinueAnalyzer <ExportLanguageServiceFactory(GetType(IEditAndContinueAnalyzer), LanguageNames.VisualBasic), [Shared]> Private NotInheritable Class Factory Implements ILanguageServiceFactory <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Function CreateLanguageService(languageServices As HostLanguageServices) As ILanguageService Implements ILanguageServiceFactory.CreateLanguageService Return New VisualBasicEditAndContinueAnalyzer(testFaultInjector:=Nothing) End Function End Class ' Public for testing purposes Public Sub New(Optional testFaultInjector As Action(Of SyntaxNode) = Nothing) MyBase.New(testFaultInjector) End Sub #Region "Syntax Analysis" Friend Overrides Function TryFindMemberDeclaration(rootOpt As SyntaxNode, node As SyntaxNode, <Out> ByRef declarations As OneOrMany(Of SyntaxNode)) As Boolean Dim current = node While current IsNot rootOpt Select Case current.Kind Case SyntaxKind.SubBlock, SyntaxKind.FunctionBlock, SyntaxKind.ConstructorBlock, SyntaxKind.OperatorBlock, SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock declarations = OneOrMany.Create(current) Return True Case SyntaxKind.PropertyStatement ' Property a As Integer = 1 ' Property a As New T If Not current.Parent.IsKind(SyntaxKind.PropertyBlock) Then declarations = OneOrMany.Create(current) Return True End If Case SyntaxKind.VariableDeclarator If current.Parent.IsKind(SyntaxKind.FieldDeclaration) Then Dim variableDeclarator = CType(current, VariableDeclaratorSyntax) If variableDeclarator.Names.Count = 1 Then declarations = OneOrMany.Create(current) Else declarations = OneOrMany.Create(variableDeclarator.Names.SelectAsArray(Function(n) CType(n, SyntaxNode))) End If Return True End If Case SyntaxKind.ModifiedIdentifier If current.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration) Then declarations = OneOrMany.Create(current) Return True End If End Select current = current.Parent End While declarations = Nothing Return False End Function ''' <summary> ''' Returns true if the <see cref="ModifiedIdentifierSyntax"/> node represents a field declaration. ''' </summary> Private Shared Function IsFieldDeclaration(node As ModifiedIdentifierSyntax) As Boolean Return node.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration) AndAlso DirectCast(node.Parent, VariableDeclaratorSyntax).Names.Count > 1 End Function ''' <summary> ''' Returns true if the <see cref="VariableDeclaratorSyntax"/> node represents a field declaration. ''' </summary> Private Shared Function IsFieldDeclaration(node As VariableDeclaratorSyntax) As Boolean Return node.Parent.IsKind(SyntaxKind.FieldDeclaration) AndAlso node.Names.Count = 1 End Function ''' <returns> ''' Given a node representing a declaration or a top-level edit node returns: ''' - <see cref="MethodBlockBaseSyntax"/> for methods, constructors, operators and accessors. ''' - <see cref="ExpressionSyntax"/> for auto-properties and fields with initializer or AsNew clause. ''' - <see cref="ArgumentListSyntax"/> for fields with array initializer, e.g. "Dim a(1) As Integer". ''' A null reference otherwise. ''' </returns> Friend Overrides Function TryGetDeclarationBody(node As SyntaxNode) As SyntaxNode Select Case node.Kind Case SyntaxKind.SubBlock, SyntaxKind.FunctionBlock, SyntaxKind.ConstructorBlock, SyntaxKind.OperatorBlock, SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock ' the body is the Statements list of the block Return node Case SyntaxKind.PropertyStatement ' the body is the initializer expression/new expression (if any) Dim propertyStatement = DirectCast(node, PropertyStatementSyntax) If propertyStatement.Initializer IsNot Nothing Then Return propertyStatement.Initializer.Value End If If HasAsNewClause(propertyStatement) Then Return DirectCast(propertyStatement.AsClause, AsNewClauseSyntax).NewExpression End If Return Nothing Case SyntaxKind.VariableDeclarator If Not node.Parent.IsKind(SyntaxKind.FieldDeclaration) Then Return Nothing End If Dim variableDeclarator = DirectCast(node, VariableDeclaratorSyntax) Dim body As SyntaxNode = Nothing If variableDeclarator.Initializer IsNot Nothing Then ' Dim a = initializer body = variableDeclarator.Initializer.Value ElseIf HasAsNewClause(variableDeclarator) Then ' Dim a As New T ' Dim a,b As New T body = DirectCast(variableDeclarator.AsClause, AsNewClauseSyntax).NewExpression End If ' Dim a(n) As T If variableDeclarator.Names.Count = 1 Then Dim name = variableDeclarator.Names(0) If name.ArrayBounds IsNot Nothing Then ' Initializer and AsNew clause can't be syntactically specified at the same time, but array bounds can be (it's a semantic error). ' Guard against such case to maintain consistency and set body to Nothing in that case. body = If(body Is Nothing, name.ArrayBounds, Nothing) End If End If Return body Case SyntaxKind.ModifiedIdentifier If Not node.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration) Then Return Nothing End If Dim modifiedIdentifier = CType(node, ModifiedIdentifierSyntax) Dim body As SyntaxNode = Nothing ' Dim a, b As New C() Dim variableDeclarator = DirectCast(node.Parent, VariableDeclaratorSyntax) If HasAsNewClause(variableDeclarator) Then body = DirectCast(variableDeclarator.AsClause, AsNewClauseSyntax).NewExpression End If ' Dim a(n) As Integer ' Dim a(n), b(n) As Integer If modifiedIdentifier.ArrayBounds IsNot Nothing Then ' AsNew clause can be syntactically specified at the same time as array bounds can be (it's a semantic error). ' Guard against such case to maintain consistency and set body to Nothing in that case. body = If(body Is Nothing, modifiedIdentifier.ArrayBounds, Nothing) End If Return body Case Else ' Note: A method without body is represented by a SubStatement. Return Nothing End Select End Function Friend Overrides Function IsDeclarationWithSharedBody(declaration As SyntaxNode) As Boolean If declaration.Kind = SyntaxKind.ModifiedIdentifier AndAlso declaration.Parent.Kind = SyntaxKind.VariableDeclarator Then Dim variableDeclarator = CType(declaration.Parent, VariableDeclaratorSyntax) Return variableDeclarator.Names.Count > 1 AndAlso variableDeclarator.Initializer IsNot Nothing OrElse HasAsNewClause(variableDeclarator) End If Return False End Function Protected Overrides Function GetCapturedVariables(model As SemanticModel, memberBody As SyntaxNode) As ImmutableArray(Of ISymbol) Dim methodBlock = TryCast(memberBody, MethodBlockBaseSyntax) If methodBlock IsNot Nothing Then If methodBlock.Statements.IsEmpty Then Return ImmutableArray(Of ISymbol).Empty End If Return model.AnalyzeDataFlow(methodBlock.Statements.First, methodBlock.Statements.Last).Captured End If Dim expression = TryCast(memberBody, ExpressionSyntax) If expression IsNot Nothing Then Return model.AnalyzeDataFlow(expression).Captured End If ' Edge case, no need to be efficient, currently there can either be no captured variables or just "Me". ' Dim a((Function(n) n + 1).Invoke(1), (Function(n) n + 2).Invoke(2)) As Integer Dim arrayBounds = TryCast(memberBody, ArgumentListSyntax) If arrayBounds IsNot Nothing Then Return ImmutableArray.CreateRange( arrayBounds.Arguments. SelectMany(AddressOf GetArgumentExpressions). SelectMany(Function(expr) model.AnalyzeDataFlow(expr).Captured). Distinct()) End If Throw ExceptionUtilities.UnexpectedValue(memberBody) End Function Private Shared Iterator Function GetArgumentExpressions(argument As ArgumentSyntax) As IEnumerable(Of ExpressionSyntax) Select Case argument.Kind Case SyntaxKind.SimpleArgument Yield DirectCast(argument, SimpleArgumentSyntax).Expression Case SyntaxKind.RangeArgument Dim range = DirectCast(argument, RangeArgumentSyntax) Yield range.LowerBound Yield range.UpperBound Case SyntaxKind.OmittedArgument Case Else Throw ExceptionUtilities.UnexpectedValue(argument.Kind) End Select End Function Friend Overrides Function HasParameterClosureScope(member As ISymbol) As Boolean Return False End Function Protected Overrides Function GetVariableUseSites(roots As IEnumerable(Of SyntaxNode), localOrParameter As ISymbol, model As SemanticModel, cancellationToken As CancellationToken) As IEnumerable(Of SyntaxNode) Debug.Assert(TypeOf localOrParameter Is IParameterSymbol OrElse TypeOf localOrParameter Is ILocalSymbol OrElse TypeOf localOrParameter Is IRangeVariableSymbol) ' Not supported (it's non trivial to find all places where "this" is used): Debug.Assert(Not localOrParameter.IsThisParameter()) Return From root In roots From node In root.DescendantNodesAndSelf() Where node.IsKind(SyntaxKind.IdentifierName) Let identifier = DirectCast(node, IdentifierNameSyntax) Where String.Equals(DirectCast(identifier.Identifier.Value, String), localOrParameter.Name, StringComparison.OrdinalIgnoreCase) AndAlso If(model.GetSymbolInfo(identifier, cancellationToken).Symbol?.Equals(localOrParameter), False) Select node End Function Private Shared Function HasAsNewClause(variableDeclarator As VariableDeclaratorSyntax) As Boolean Return variableDeclarator.AsClause IsNot Nothing AndAlso variableDeclarator.AsClause.IsKind(SyntaxKind.AsNewClause) End Function Private Shared Function HasAsNewClause(propertyStatement As PropertyStatementSyntax) As Boolean Return propertyStatement.AsClause IsNot Nothing AndAlso propertyStatement.AsClause.IsKind(SyntaxKind.AsNewClause) End Function ''' <returns> ''' Methods, operators, constructors, property and event accessors: ''' - We need to return the entire block declaration since the Begin and End statements are covered by breakpoint spans. ''' Field declarations in form of "Dim a, b, c As New C()" ''' - Breakpoint spans cover "a", "b" and "c" and also "New C()" since the expression may contain lambdas. ''' For simplicity we don't allow moving the new expression independently of the field name. ''' Field declarations with array initializers "Dim a(n), b(n) As Integer" ''' - Breakpoint spans cover "a(n)" and "b(n)". ''' </returns> Friend Overrides Function TryGetActiveTokens(node As SyntaxNode) As IEnumerable(Of SyntaxToken) Select Case node.Kind Case SyntaxKind.SubBlock, SyntaxKind.FunctionBlock, SyntaxKind.ConstructorBlock, SyntaxKind.OperatorBlock, SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock ' the body is the Statements list of the block Return node.DescendantTokens() Case SyntaxKind.PropertyStatement ' Property: Attributes Modifiers [|Identifier AsClause Initializer|] ImplementsClause ' Property: Attributes Modifiers [|Identifier$ Initializer|] ImplementsClause Dim propertyStatement = DirectCast(node, PropertyStatementSyntax) If propertyStatement.Initializer IsNot Nothing Then Return SpecializedCollections.SingletonEnumerable(propertyStatement.Identifier).Concat(If(propertyStatement.AsClause?.DescendantTokens(), Array.Empty(Of SyntaxToken))).Concat(propertyStatement.Initializer.DescendantTokens()) End If If HasAsNewClause(propertyStatement) Then Return SpecializedCollections.SingletonEnumerable(propertyStatement.Identifier).Concat(propertyStatement.AsClause.DescendantTokens()) End If Return Nothing Case SyntaxKind.VariableDeclarator Dim variableDeclarator = DirectCast(node, VariableDeclaratorSyntax) If Not IsFieldDeclaration(variableDeclarator) Then Return Nothing End If ' Field: Attributes Modifiers Declarators Dim fieldDeclaration = DirectCast(node.Parent, FieldDeclarationSyntax) If fieldDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword) Then Return Nothing End If ' Dim a = initializer If variableDeclarator.Initializer IsNot Nothing Then Return variableDeclarator.DescendantTokens() End If ' Dim a As New C() If HasAsNewClause(variableDeclarator) Then Return variableDeclarator.DescendantTokens() End If ' Dim a(n) As Integer Dim modifiedIdentifier = variableDeclarator.Names.Single() If modifiedIdentifier.ArrayBounds IsNot Nothing Then Return variableDeclarator.DescendantTokens() End If Return Nothing Case SyntaxKind.ModifiedIdentifier Dim modifiedIdentifier = DirectCast(node, ModifiedIdentifierSyntax) If Not IsFieldDeclaration(modifiedIdentifier) Then Return Nothing End If ' Dim a, b As New C() Dim variableDeclarator = DirectCast(node.Parent, VariableDeclaratorSyntax) If HasAsNewClause(variableDeclarator) Then Return node.DescendantTokens().Concat(DirectCast(variableDeclarator.AsClause, AsNewClauseSyntax).NewExpression.DescendantTokens()) End If ' Dim a(n), b(n) As Integer If modifiedIdentifier.ArrayBounds IsNot Nothing Then Return node.DescendantTokens() End If Return Nothing Case Else Return Nothing End Select End Function Friend Overrides Function GetActiveSpanEnvelope(declaration As SyntaxNode) As (envelope As TextSpan, hole As TextSpan) Select Case declaration.Kind Case SyntaxKind.SubBlock, SyntaxKind.FunctionBlock, SyntaxKind.ConstructorBlock, SyntaxKind.OperatorBlock, SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock ' the body is the Statements list of the block Return (declaration.Span, Nothing) Case SyntaxKind.PropertyStatement ' Property: Attributes Modifiers [|Identifier AsClause Initializer|] ImplementsClause ' Property: Attributes Modifiers [|Identifier$ Initializer|] ImplementsClause Dim propertyStatement = DirectCast(declaration, PropertyStatementSyntax) If propertyStatement.Initializer IsNot Nothing Then Return (TextSpan.FromBounds(propertyStatement.Identifier.Span.Start, propertyStatement.Initializer.Span.End), Nothing) End If If HasAsNewClause(propertyStatement) Then Return (TextSpan.FromBounds(propertyStatement.Identifier.Span.Start, propertyStatement.AsClause.Span.End), Nothing) End If Return Nothing Case SyntaxKind.VariableDeclarator Dim variableDeclarator = DirectCast(declaration, VariableDeclaratorSyntax) If Not declaration.Parent.IsKind(SyntaxKind.FieldDeclaration) OrElse variableDeclarator.Names.Count > 1 Then Return Nothing End If ' Field: Attributes Modifiers Declarators Dim fieldDeclaration = DirectCast(declaration.Parent, FieldDeclarationSyntax) If fieldDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword) Then Return Nothing End If ' Dim a = initializer If variableDeclarator.Initializer IsNot Nothing Then Return (variableDeclarator.Span, Nothing) End If ' Dim a As New C() If HasAsNewClause(variableDeclarator) Then Return (variableDeclarator.Span, Nothing) End If ' Dim a(n) As Integer Dim modifiedIdentifier = variableDeclarator.Names.Single() If modifiedIdentifier.ArrayBounds IsNot Nothing Then Return (variableDeclarator.Span, Nothing) End If Return Nothing Case SyntaxKind.ModifiedIdentifier If Not declaration.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration) Then Return Nothing End If ' Dim a, b As New C() Dim variableDeclarator = DirectCast(declaration.Parent, VariableDeclaratorSyntax) If HasAsNewClause(variableDeclarator) Then Dim asNewClause = DirectCast(variableDeclarator.AsClause, AsNewClauseSyntax) Return (envelope:=TextSpan.FromBounds(declaration.Span.Start, asNewClause.NewExpression.Span.End), hole:=TextSpan.FromBounds(declaration.Span.End, asNewClause.NewExpression.Span.Start)) End If ' Dim a(n) As Integer ' Dim a(n), b(n) As Integer Dim modifiedIdentifier = DirectCast(declaration, ModifiedIdentifierSyntax) If modifiedIdentifier.ArrayBounds IsNot Nothing Then Return (declaration.Span, Nothing) End If Return Nothing Case Else Return Nothing End Select End Function Protected Overrides Function GetEncompassingAncestorImpl(bodyOrMatchRoot As SyntaxNode) As SyntaxNode ' AsNewClause is a match root for field/property As New initializer ' EqualsClause is a match root for field/property initializer If bodyOrMatchRoot.IsKind(SyntaxKind.AsNewClause) OrElse bodyOrMatchRoot.IsKind(SyntaxKind.EqualsValue) Then Debug.Assert(bodyOrMatchRoot.Parent.IsKind(SyntaxKind.VariableDeclarator) OrElse bodyOrMatchRoot.Parent.IsKind(SyntaxKind.PropertyStatement)) Return bodyOrMatchRoot.Parent End If ' ArgumentList is a match root for an array initialized field If bodyOrMatchRoot.IsKind(SyntaxKind.ArgumentList) Then Debug.Assert(bodyOrMatchRoot.Parent.IsKind(SyntaxKind.ModifiedIdentifier)) Return bodyOrMatchRoot.Parent End If ' The following active nodes are outside of the initializer body, ' we need to return a node that encompasses them. ' Dim [|a = <<Body>>|] ' Dim [|a As Integer = <<Body>>|] ' Dim [|a As <<Body>>|] ' Dim [|a|], [|b|], [|c|] As <<Body>> ' Property [|P As Integer = <<Body>>|] ' Property [|P As <<Body>>|] If bodyOrMatchRoot.Parent.IsKind(SyntaxKind.AsNewClause) OrElse bodyOrMatchRoot.Parent.IsKind(SyntaxKind.EqualsValue) Then Return bodyOrMatchRoot.Parent.Parent End If Return bodyOrMatchRoot End Function Protected Overrides Function FindStatementAndPartner(declarationBody As SyntaxNode, span As TextSpan, partnerDeclarationBodyOpt As SyntaxNode, <Out> ByRef partnerOpt As SyntaxNode, <Out> ByRef statementPart As Integer) As SyntaxNode Dim position = span.Start SyntaxUtilities.AssertIsBody(declarationBody, allowLambda:=False) Debug.Assert(partnerDeclarationBodyOpt Is Nothing OrElse partnerDeclarationBodyOpt.RawKind = declarationBody.RawKind) ' Only field and property initializers may have an [|active statement|] starting outside of the <<body>>. ' Simple field initializers: Dim [|a = <<expr>>|] ' Dim [|a As Integer = <<expr>>|] ' Dim [|a = <<expr>>|], [|b = <<expr>>|], [|c As Integer = <<expr>>|] ' Dim [|a As <<New C>>|] ' Array initialized fields: Dim [|a<<(array bounds)>>|] As Integer ' Shared initializers: Dim [|a|], [|b|] As <<New C(Function() [|...|])>> ' Property initializers: Property [|p As Integer = <<body>>|] ' Property [|p As <<New C()>>|] If position < declarationBody.SpanStart Then If declarationBody.Parent.Parent.IsKind(SyntaxKind.PropertyStatement) Then ' Property [|p As Integer = <<body>>|] ' Property [|p As <<New C()>>|] If partnerDeclarationBodyOpt IsNot Nothing Then partnerOpt = partnerDeclarationBodyOpt.Parent.Parent End If Debug.Assert(declarationBody.Parent.Parent.IsKind(SyntaxKind.PropertyStatement)) Return declarationBody.Parent.Parent End If If declarationBody.IsKind(SyntaxKind.ArgumentList) Then ' Dim a<<ArgumentList>> As Integer If partnerDeclarationBodyOpt IsNot Nothing Then partnerOpt = partnerDeclarationBodyOpt.Parent End If Debug.Assert(declarationBody.Parent.IsKind(SyntaxKind.ModifiedIdentifier)) Return declarationBody.Parent End If If declarationBody.Parent.IsKind(SyntaxKind.AsNewClause) Then Dim variableDeclarator = DirectCast(declarationBody.Parent.Parent, VariableDeclaratorSyntax) If variableDeclarator.Names.Count > 1 Then ' Dim a, b, c As <<NewExpression>> Dim nameIndex = GetItemIndexByPosition(variableDeclarator.Names, position) If partnerDeclarationBodyOpt IsNot Nothing Then partnerOpt = DirectCast(partnerDeclarationBodyOpt.Parent.Parent, VariableDeclaratorSyntax).Names(nameIndex) End If Return variableDeclarator.Names(nameIndex) Else If partnerDeclarationBodyOpt IsNot Nothing Then partnerOpt = partnerDeclarationBodyOpt.Parent.Parent End If ' Dim a As <<NewExpression>> Return variableDeclarator End If End If If declarationBody.Parent.IsKind(SyntaxKind.EqualsValue) Then Debug.Assert(declarationBody.Parent.Parent.IsKind(SyntaxKind.VariableDeclarator) AndAlso declarationBody.Parent.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration)) If partnerDeclarationBodyOpt IsNot Nothing Then partnerOpt = partnerDeclarationBodyOpt.Parent.Parent End If Return declarationBody.Parent.Parent End If End If If Not declarationBody.FullSpan.Contains(position) Then ' invalid position, let's find a labeled node that encompasses the body: position = declarationBody.SpanStart End If Dim node As SyntaxNode = Nothing If partnerDeclarationBodyOpt IsNot Nothing Then SyntaxUtilities.FindLeafNodeAndPartner(declarationBody, position, partnerDeclarationBodyOpt, node, partnerOpt) Else node = declarationBody.FindToken(position).Parent partnerOpt = Nothing End If ' In some cases active statements may start at the same position. ' Consider a nested lambda: ' Function(a) [|[|Function(b)|] a + b|] ' There are 2 active statements, one spanning the the body of the outer lambda and ' the other on the nested lambda's header. ' Find the parent whose span starts at the same position but it's length is at least as long as the active span's length. While node.Span.Length < span.Length AndAlso node.Parent.SpanStart = position node = node.Parent partnerOpt = partnerOpt?.Parent End While Debug.Assert(node IsNot Nothing) While node IsNot declarationBody AndAlso Not SyntaxComparer.Statement.HasLabel(node) AndAlso Not LambdaUtilities.IsLambdaBodyStatementOrExpression(node) node = node.Parent If partnerOpt IsNot Nothing Then partnerOpt = partnerOpt.Parent End If End While ' In case of local variable declaration an active statement may start with a modified identifier. ' If it is a declaration with a simple initializer we want the resulting statement to be the declaration, ' not the identifier. If node.IsKind(SyntaxKind.ModifiedIdentifier) AndAlso node.Parent.IsKind(SyntaxKind.VariableDeclarator) AndAlso DirectCast(node.Parent, VariableDeclaratorSyntax).Names.Count = 1 Then node = node.Parent End If Return node End Function Friend Overrides Function FindDeclarationBodyPartner(leftDeclaration As SyntaxNode, rightDeclaration As SyntaxNode, leftNode As SyntaxNode) As SyntaxNode Debug.Assert(leftDeclaration.Kind = rightDeclaration.Kind) ' Special case modified identifiers with AsNew clause - the node we are seeking can be in the AsNew clause. If leftDeclaration.Kind = SyntaxKind.ModifiedIdentifier Then Dim leftDeclarator = CType(leftDeclaration.Parent, VariableDeclaratorSyntax) Dim rightDeclarator = CType(rightDeclaration.Parent, VariableDeclaratorSyntax) If leftDeclarator.AsClause IsNot Nothing AndAlso leftNode.SpanStart >= leftDeclarator.AsClause.SpanStart Then Return SyntaxUtilities.FindPartner(leftDeclarator.AsClause, rightDeclarator.AsClause, leftNode) End If End If Return SyntaxUtilities.FindPartner(leftDeclaration, rightDeclaration, leftNode) End Function Friend Overrides Function IsClosureScope(node As SyntaxNode) As Boolean Return LambdaUtilities.IsClosureScope(node) End Function Protected Overrides Function FindEnclosingLambdaBody(containerOpt As SyntaxNode, node As SyntaxNode) As SyntaxNode Dim root As SyntaxNode = GetEncompassingAncestor(containerOpt) While node IsNot root And node IsNot Nothing Dim body As SyntaxNode = Nothing If LambdaUtilities.IsLambdaBodyStatementOrExpression(node, body) Then Return body End If node = node.Parent End While Return Nothing End Function Protected Overrides Function TryGetPartnerLambdaBody(oldBody As SyntaxNode, newLambda As SyntaxNode) As SyntaxNode Return LambdaUtilities.GetCorrespondingLambdaBody(oldBody, newLambda) End Function Protected Overrides Function ComputeTopLevelMatch(oldCompilationUnit As SyntaxNode, newCompilationUnit As SyntaxNode) As Match(Of SyntaxNode) Return SyntaxComparer.TopLevel.ComputeMatch(oldCompilationUnit, newCompilationUnit) End Function Protected Overrides Function ComputeTopLevelDeclarationMatch(oldDeclaration As SyntaxNode, newDeclaration As SyntaxNode) As Match(Of SyntaxNode) Contract.ThrowIfNull(oldDeclaration.Parent) Contract.ThrowIfNull(newDeclaration.Parent) ' Allow matching field declarations represented by a identitifer and the whole variable declarator ' even when their node kinds do not match. If oldDeclaration.IsKind(SyntaxKind.ModifiedIdentifier) AndAlso newDeclaration.IsKind(SyntaxKind.VariableDeclarator) Then oldDeclaration = oldDeclaration.Parent ElseIf oldDeclaration.IsKind(SyntaxKind.VariableDeclarator) AndAlso newDeclaration.IsKind(SyntaxKind.ModifiedIdentifier) Then newDeclaration = newDeclaration.Parent End If Dim comparer = New SyntaxComparer(oldDeclaration.Parent, newDeclaration.Parent, {oldDeclaration}, {newDeclaration}) Return comparer.ComputeMatch(oldDeclaration.Parent, newDeclaration.Parent) End Function Protected Overrides Function ComputeBodyMatch(oldBody As SyntaxNode, newBody As SyntaxNode, knownMatches As IEnumerable(Of KeyValuePair(Of SyntaxNode, SyntaxNode))) As Match(Of SyntaxNode) SyntaxUtilities.AssertIsBody(oldBody, allowLambda:=True) SyntaxUtilities.AssertIsBody(newBody, allowLambda:=True) Debug.Assert((TypeOf oldBody.Parent Is LambdaExpressionSyntax) = (TypeOf oldBody.Parent Is LambdaExpressionSyntax)) Debug.Assert((TypeOf oldBody Is ExpressionSyntax) = (TypeOf newBody Is ExpressionSyntax)) Debug.Assert((TypeOf oldBody Is ArgumentListSyntax) = (TypeOf newBody Is ArgumentListSyntax)) If TypeOf oldBody.Parent Is LambdaExpressionSyntax Then ' The root is a single/multi line sub/function lambda. Return New SyntaxComparer(oldBody.Parent, newBody.Parent, oldBody.Parent.ChildNodes(), newBody.Parent.ChildNodes(), matchingLambdas:=True, compareStatementSyntax:=True). ComputeMatch(oldBody.Parent, newBody.Parent, knownMatches) End If If TypeOf oldBody Is ExpressionSyntax Then ' Dim a = <Expression> ' Dim a As <NewExpression> ' Dim a, b, c As <NewExpression> ' Queries: The root is a query clause, the body is the expression. Return New SyntaxComparer(oldBody.Parent, newBody.Parent, {oldBody}, {newBody}, matchingLambdas:=False, compareStatementSyntax:=True). ComputeMatch(oldBody.Parent, newBody.Parent, knownMatches) End If ' Method, accessor, operator, etc. bodies are represented by the declaring block, which is also the root. ' The body of an array initialized fields is an ArgumentListSyntax, which is the match root. Return SyntaxComparer.Statement.ComputeMatch(oldBody, newBody, knownMatches) End Function Protected Overrides Function TryMatchActiveStatement(oldStatement As SyntaxNode, statementPart As Integer, oldBody As SyntaxNode, newBody As SyntaxNode, <Out> ByRef newStatement As SyntaxNode) As Boolean SyntaxUtilities.AssertIsBody(oldBody, allowLambda:=True) SyntaxUtilities.AssertIsBody(newBody, allowLambda:=True) ' only statements in bodies of the same kind can be matched Debug.Assert((TypeOf oldBody Is MethodBlockBaseSyntax) = (TypeOf newBody Is MethodBlockBaseSyntax)) Debug.Assert((TypeOf oldBody Is ExpressionSyntax) = (TypeOf newBody Is ExpressionSyntax)) Debug.Assert((TypeOf oldBody Is ArgumentListSyntax) = (TypeOf newBody Is ArgumentListSyntax)) Debug.Assert((TypeOf oldBody Is LambdaHeaderSyntax) = (TypeOf newBody Is LambdaHeaderSyntax)) Debug.Assert(oldBody.Parent.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration) = newBody.Parent.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration)) Debug.Assert(oldBody.Parent.Parent.IsKind(SyntaxKind.PropertyStatement) = newBody.Parent.Parent.IsKind(SyntaxKind.PropertyStatement)) ' methods If TypeOf oldBody Is MethodBlockBaseSyntax Then newStatement = Nothing Return False End If ' lambdas If oldBody.IsKind(SyntaxKind.FunctionLambdaHeader) OrElse oldBody.IsKind(SyntaxKind.SubLambdaHeader) Then Dim oldSingleLineLambda = TryCast(oldBody.Parent, SingleLineLambdaExpressionSyntax) Dim newSingleLineLambda = TryCast(newBody.Parent, SingleLineLambdaExpressionSyntax) If oldSingleLineLambda IsNot Nothing AndAlso newSingleLineLambda IsNot Nothing AndAlso oldStatement Is oldSingleLineLambda.Body Then newStatement = newSingleLineLambda.Body Return True End If newStatement = Nothing Return False End If ' array initialized fields If newBody.IsKind(SyntaxKind.ArgumentList) Then ' the parent ModifiedIdentifier is the active statement If oldStatement Is oldBody.Parent Then newStatement = newBody.Parent Return True End If newStatement = Nothing Return False End If ' field and property initializers If TypeOf newBody Is ExpressionSyntax Then If newBody.Parent.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration) Then ' field Dim newDeclarator = DirectCast(newBody.Parent.Parent, VariableDeclaratorSyntax) Dim oldName As SyntaxToken If oldStatement.IsKind(SyntaxKind.VariableDeclarator) Then oldName = DirectCast(oldStatement, VariableDeclaratorSyntax).Names.Single.Identifier Else oldName = DirectCast(oldStatement, ModifiedIdentifierSyntax).Identifier End If For Each newName In newDeclarator.Names If SyntaxFactory.AreEquivalent(newName.Identifier, oldName) Then newStatement = newName Return True End If Next newStatement = Nothing Return False ElseIf newBody.Parent.Parent.IsKind(SyntaxKind.PropertyStatement) Then ' property If oldStatement Is oldBody.Parent.Parent Then newStatement = newBody.Parent.Parent Return True End If newStatement = newBody Return True End If End If ' queries If oldStatement Is oldBody Then newStatement = newBody Return True End If newStatement = Nothing Return False End Function #End Region #Region "Syntax And Semantic Utils" Protected Overrides Function GetGlobalStatementDiagnosticSpan(node As SyntaxNode) As TextSpan Return Nothing End Function Protected Overrides ReadOnly Property LineDirectiveKeyword As String Get Return "ExternalSource" End Get End Property Protected Overrides ReadOnly Property LineDirectiveSyntaxKind As UShort Get Return SyntaxKind.ExternalSourceDirectiveTrivia End Get End Property Protected Overrides Function GetSyntaxSequenceEdits(oldNodes As ImmutableArray(Of SyntaxNode), newNodes As ImmutableArray(Of SyntaxNode)) As IEnumerable(Of SequenceEdit) Return SyntaxComparer.GetSequenceEdits(oldNodes, newNodes) End Function Friend Overrides ReadOnly Property EmptyCompilationUnit As SyntaxNode Get Return SyntaxFactory.CompilationUnit() End Get End Property Friend Overrides Function ExperimentalFeaturesEnabled(tree As SyntaxTree) As Boolean ' There are no experimental features at this time. Return False End Function Protected Overrides Function StatementLabelEquals(node1 As SyntaxNode, node2 As SyntaxNode) As Boolean Return SyntaxComparer.Statement.GetLabelImpl(node1) = SyntaxComparer.Statement.GetLabelImpl(node2) End Function Private Shared Function GetItemIndexByPosition(Of TNode As SyntaxNode)(list As SeparatedSyntaxList(Of TNode), position As Integer) As Integer For i = list.SeparatorCount - 1 To 0 Step -1 If position > list.GetSeparator(i).SpanStart Then Return i + 1 End If Next Return 0 End Function Private Shared Function ChildrenCompiledInBody(node As SyntaxNode) As Boolean Return Not node.IsKind(SyntaxKind.MultiLineFunctionLambdaExpression) AndAlso Not node.IsKind(SyntaxKind.SingleLineFunctionLambdaExpression) AndAlso Not node.IsKind(SyntaxKind.MultiLineSubLambdaExpression) AndAlso Not node.IsKind(SyntaxKind.SingleLineSubLambdaExpression) End Function Protected Overrides Function TryGetEnclosingBreakpointSpan(root As SyntaxNode, position As Integer, <Out> ByRef span As TextSpan) As Boolean Return BreakpointSpans.TryGetEnclosingBreakpointSpan(root, position, minLength:=0, span) End Function Protected Overrides Function TryGetActiveSpan(node As SyntaxNode, statementPart As Integer, minLength As Integer, <Out> ByRef span As TextSpan) As Boolean Return BreakpointSpans.TryGetEnclosingBreakpointSpan(node, node.SpanStart, minLength, span) End Function Protected Overrides Iterator Function EnumerateNearStatements(statement As SyntaxNode) As IEnumerable(Of ValueTuple(Of SyntaxNode, Integer)) Dim direction As Integer = +1 Dim nodeOrToken As SyntaxNodeOrToken = statement Dim propertyOrFieldModifiers As SyntaxTokenList? = GetFieldOrPropertyModifiers(statement) While True ' If the current statement is the last statement of if-block or try-block statements ' pretend there are no siblings following it. Dim lastBlockStatement As SyntaxNode = Nothing If nodeOrToken.Parent IsNot Nothing Then If nodeOrToken.Parent.IsKind(SyntaxKind.MultiLineIfBlock) Then lastBlockStatement = DirectCast(nodeOrToken.Parent, MultiLineIfBlockSyntax).Statements.LastOrDefault() ElseIf nodeOrToken.Parent.IsKind(SyntaxKind.SingleLineIfStatement) Then lastBlockStatement = DirectCast(nodeOrToken.Parent, SingleLineIfStatementSyntax).Statements.LastOrDefault() ElseIf nodeOrToken.Parent.IsKind(SyntaxKind.TryBlock) Then lastBlockStatement = DirectCast(nodeOrToken.Parent, TryBlockSyntax).Statements.LastOrDefault() End If End If If direction > 0 Then If lastBlockStatement IsNot Nothing AndAlso nodeOrToken.AsNode() Is lastBlockStatement Then nodeOrToken = Nothing Else nodeOrToken = nodeOrToken.GetNextSibling() End If Else nodeOrToken = nodeOrToken.GetPreviousSibling() If lastBlockStatement IsNot Nothing AndAlso nodeOrToken.AsNode() Is lastBlockStatement Then nodeOrToken = Nothing End If End If If nodeOrToken.RawKind = 0 Then Dim parent = statement.Parent If parent Is Nothing Then Return End If If direction > 0 Then nodeOrToken = statement direction = -1 Continue While End If If propertyOrFieldModifiers.HasValue Then Yield (statement, -1) End If nodeOrToken = parent statement = parent propertyOrFieldModifiers = GetFieldOrPropertyModifiers(statement) direction = +1 End If Dim node = nodeOrToken.AsNode() If node Is Nothing Then Continue While End If If propertyOrFieldModifiers.HasValue Then Dim nodeModifiers = GetFieldOrPropertyModifiers(node) If Not nodeModifiers.HasValue OrElse propertyOrFieldModifiers.Value.Any(SyntaxKind.SharedKeyword) <> nodeModifiers.Value.Any(SyntaxKind.SharedKeyword) Then Continue While End If End If Yield (node, DefaultStatementPart) End While End Function Private Shared Function GetFieldOrPropertyModifiers(node As SyntaxNode) As SyntaxTokenList? If node.IsKind(SyntaxKind.FieldDeclaration) Then Return DirectCast(node, FieldDeclarationSyntax).Modifiers ElseIf node.IsKind(SyntaxKind.PropertyStatement) Then Return DirectCast(node, PropertyStatementSyntax).Modifiers Else Return Nothing End If End Function Protected Overrides Function AreEquivalent(left As SyntaxNode, right As SyntaxNode) As Boolean Return SyntaxFactory.AreEquivalent(left, right) End Function Private Shared Function AreEquivalentIgnoringLambdaBodies(left As SyntaxNode, right As SyntaxNode) As Boolean ' usual case If SyntaxFactory.AreEquivalent(left, right) Then Return True End If Return LambdaUtilities.AreEquivalentIgnoringLambdaBodies(left, right) End Function Protected Overrides Function AreEquivalentActiveStatements(oldStatement As SyntaxNode, newStatement As SyntaxNode, statementPart As Integer) As Boolean If oldStatement.RawKind <> newStatement.RawKind Then Return False End If ' Dim a,b,c As <NewExpression> ' We need to check the actual initializer expression in addition to the identifier. If HasMultiInitializer(oldStatement) Then Return AreEquivalentIgnoringLambdaBodies(oldStatement, newStatement) AndAlso AreEquivalentIgnoringLambdaBodies(DirectCast(oldStatement.Parent, VariableDeclaratorSyntax).AsClause, DirectCast(newStatement.Parent, VariableDeclaratorSyntax).AsClause) End If Select Case oldStatement.Kind Case SyntaxKind.SubNewStatement, SyntaxKind.SubStatement, SyntaxKind.SubNewStatement, SyntaxKind.FunctionStatement, SyntaxKind.OperatorStatement, SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorStatement, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorStatement ' Header statements are nops. Changes in the header statements are changes in top-level surface ' which should not be reported as active statement rude edits. Return True Case Else Return AreEquivalentIgnoringLambdaBodies(oldStatement, newStatement) End Select End Function Private Shared Function HasMultiInitializer(modifiedIdentifier As SyntaxNode) As Boolean Return modifiedIdentifier.Parent.IsKind(SyntaxKind.VariableDeclarator) AndAlso DirectCast(modifiedIdentifier.Parent, VariableDeclaratorSyntax).Names.Count > 1 End Function Friend Overrides Function IsInterfaceDeclaration(node As SyntaxNode) As Boolean Return node.IsKind(SyntaxKind.InterfaceBlock) End Function Friend Overrides Function IsRecordDeclaration(node As SyntaxNode) As Boolean ' No records in VB Return False End Function Friend Overrides Function TryGetContainingTypeDeclaration(node As SyntaxNode) As SyntaxNode Return node.Parent.FirstAncestorOrSelf(Of TypeBlockSyntax)() ' TODO: EnbumBlock? End Function Friend Overrides Function TryGetAssociatedMemberDeclaration(node As SyntaxNode, <Out> ByRef declaration As SyntaxNode) As Boolean If node.IsKind(SyntaxKind.Parameter, SyntaxKind.TypeParameter) Then Contract.ThrowIfFalse(node.IsParentKind(SyntaxKind.ParameterList, SyntaxKind.TypeParameterList)) declaration = node.Parent.Parent Return True End If If node.IsParentKind(SyntaxKind.PropertyBlock, SyntaxKind.EventBlock) Then declaration = node.Parent Return True End If declaration = Nothing Return False End Function Friend Overrides Function HasBackingField(propertyDeclaration As SyntaxNode) As Boolean Return SyntaxUtilities.HasBackingField(propertyDeclaration) End Function Friend Overrides Function IsDeclarationWithInitializer(declaration As SyntaxNode) As Boolean Select Case declaration.Kind Case SyntaxKind.VariableDeclarator Dim declarator = DirectCast(declaration, VariableDeclaratorSyntax) Return GetInitializerExpression(declarator.Initializer, declarator.AsClause) IsNot Nothing OrElse declarator.Names.Any(Function(n) n.ArrayBounds IsNot Nothing) Case SyntaxKind.ModifiedIdentifier Debug.Assert(declaration.Parent.IsKind(SyntaxKind.VariableDeclarator) OrElse declaration.Parent.IsKind(SyntaxKind.Parameter)) If Not declaration.Parent.IsKind(SyntaxKind.VariableDeclarator) Then Return False End If Dim declarator = DirectCast(declaration.Parent, VariableDeclaratorSyntax) Dim identifier = DirectCast(declaration, ModifiedIdentifierSyntax) Return identifier.ArrayBounds IsNot Nothing OrElse GetInitializerExpression(declarator.Initializer, declarator.AsClause) IsNot Nothing Case SyntaxKind.PropertyStatement Dim propertyStatement = DirectCast(declaration, PropertyStatementSyntax) Return GetInitializerExpression(propertyStatement.Initializer, propertyStatement.AsClause) IsNot Nothing Case Else Return False End Select End Function Friend Overrides Function IsRecordPrimaryConstructorParameter(declaration As SyntaxNode) As Boolean Return False End Function Friend Overrides Function IsPropertyAccessorDeclarationMatchingPrimaryConstructorParameter(declaration As SyntaxNode, newContainingType As INamedTypeSymbol, ByRef isFirstAccessor As Boolean) As Boolean Return False End Function Private Shared Function GetInitializerExpression(equalsValue As EqualsValueSyntax, asClause As AsClauseSyntax) As ExpressionSyntax If equalsValue IsNot Nothing Then Return equalsValue.Value End If If asClause IsNot Nothing AndAlso asClause.IsKind(SyntaxKind.AsNewClause) Then Return DirectCast(asClause, AsNewClauseSyntax).NewExpression End If Return Nothing End Function ''' <summary> ''' VB symbols return references that represent the declaration statement. ''' The node that represenets the whole declaration (the block) is the parent node if it exists. ''' For example, a method with a body is represented by a SubBlock/FunctionBlock while a method without a body ''' is represented by its declaration statement. ''' </summary> Protected Overrides Function GetSymbolDeclarationSyntax(reference As SyntaxReference, cancellationToken As CancellationToken) As SyntaxNode Dim syntax = reference.GetSyntax(cancellationToken) Dim parent = syntax.Parent Select Case syntax.Kind ' declarations that always have block Case SyntaxKind.NamespaceStatement Debug.Assert(parent.Kind = SyntaxKind.NamespaceBlock) Return parent Case SyntaxKind.ClassStatement Debug.Assert(parent.Kind = SyntaxKind.ClassBlock) Return parent Case SyntaxKind.StructureStatement Debug.Assert(parent.Kind = SyntaxKind.StructureBlock) Return parent Case SyntaxKind.InterfaceStatement Debug.Assert(parent.Kind = SyntaxKind.InterfaceBlock) Return parent Case SyntaxKind.ModuleStatement Debug.Assert(parent.Kind = SyntaxKind.ModuleBlock) Return parent Case SyntaxKind.EnumStatement Debug.Assert(parent.Kind = SyntaxKind.EnumBlock) Return parent Case SyntaxKind.SubNewStatement Debug.Assert(parent.Kind = SyntaxKind.ConstructorBlock) Return parent Case SyntaxKind.OperatorStatement Debug.Assert(parent.Kind = SyntaxKind.OperatorBlock) Return parent Case SyntaxKind.GetAccessorStatement Debug.Assert(parent.Kind = SyntaxKind.GetAccessorBlock) Return parent Case SyntaxKind.SetAccessorStatement Debug.Assert(parent.Kind = SyntaxKind.SetAccessorBlock) Return parent Case SyntaxKind.AddHandlerAccessorStatement Debug.Assert(parent.Kind = SyntaxKind.AddHandlerAccessorBlock) Return parent Case SyntaxKind.RemoveHandlerAccessorStatement Debug.Assert(parent.Kind = SyntaxKind.RemoveHandlerAccessorBlock) Return parent Case SyntaxKind.RaiseEventAccessorStatement Debug.Assert(parent.Kind = SyntaxKind.RaiseEventAccessorBlock) Return parent ' declarations that may or may not have block Case SyntaxKind.SubStatement Return If(parent.Kind = SyntaxKind.SubBlock, parent, syntax) Case SyntaxKind.FunctionStatement Return If(parent.Kind = SyntaxKind.FunctionBlock, parent, syntax) Case SyntaxKind.PropertyStatement Return If(parent.Kind = SyntaxKind.PropertyBlock, parent, syntax) Case SyntaxKind.EventStatement Return If(parent.Kind = SyntaxKind.EventBlock, parent, syntax) ' declarations that never have a block Case SyntaxKind.ModifiedIdentifier Contract.ThrowIfFalse(parent.Parent.IsKind(SyntaxKind.FieldDeclaration)) Dim variableDeclaration = CType(parent, VariableDeclaratorSyntax) Return If(variableDeclaration.Names.Count = 1, parent, syntax) Case SyntaxKind.VariableDeclarator ' fields are represented by ModifiedIdentifier: Throw ExceptionUtilities.UnexpectedValue(syntax.Kind) Case Else Return syntax End Select End Function Friend Overrides Function IsConstructorWithMemberInitializers(declaration As SyntaxNode) As Boolean Dim ctor = TryCast(declaration, ConstructorBlockSyntax) If ctor Is Nothing Then Return False End If ' Constructor includes field initializers if the first statement ' isn't a call to another constructor of the declaring class or module. If ctor.Statements.Count = 0 Then Return True End If Dim firstStatement = ctor.Statements.First If Not firstStatement.IsKind(SyntaxKind.ExpressionStatement) Then Return True End If Dim expressionStatement = DirectCast(firstStatement, ExpressionStatementSyntax) If Not expressionStatement.Expression.IsKind(SyntaxKind.InvocationExpression) Then Return True End If Dim invocation = DirectCast(expressionStatement.Expression, InvocationExpressionSyntax) If Not invocation.Expression.IsKind(SyntaxKind.SimpleMemberAccessExpression) Then Return True End If Dim memberAccess = DirectCast(invocation.Expression, MemberAccessExpressionSyntax) If Not memberAccess.Name.IsKind(SyntaxKind.IdentifierName) OrElse Not memberAccess.Name.Identifier.IsKind(SyntaxKind.IdentifierToken) Then Return True End If ' Note that ValueText returns "New" for both New and [New] If Not String.Equals(memberAccess.Name.Identifier.ToString(), "New", StringComparison.OrdinalIgnoreCase) Then Return True End If Return memberAccess.Expression.IsKind(SyntaxKind.MyBaseKeyword) End Function Friend Overrides Function IsPartial(type As INamedTypeSymbol) As Boolean Dim syntaxRefs = type.DeclaringSyntaxReferences Return syntaxRefs.Length > 1 OrElse DirectCast(syntaxRefs.Single().GetSyntax(), TypeStatementSyntax).Modifiers.Any(SyntaxKind.PartialKeyword) End Function Protected Overrides Function GetSymbolEdits( editKind As EditKind, oldNode As SyntaxNode, newNode As SyntaxNode, oldModel As SemanticModel, newModel As SemanticModel, editMap As IReadOnlyDictionary(Of SyntaxNode, EditKind), cancellationToken As CancellationToken) As OneOrMany(Of (oldSymbol As ISymbol, newSymbol As ISymbol, editKind As EditKind)) Dim oldSymbols As OneOrMany(Of ISymbol) = Nothing Dim newSymbols As OneOrMany(Of ISymbol) = Nothing If editKind = EditKind.Delete Then If Not TryGetSyntaxNodesForEdit(editKind, oldNode, oldModel, oldSymbols, cancellationToken) Then Return OneOrMany(Of (ISymbol, ISymbol, EditKind)).Empty End If Return oldSymbols.Select(Function(s) New ValueTuple(Of ISymbol, ISymbol, EditKind)(s, Nothing, editKind)) End If If editKind = EditKind.Insert Then If Not TryGetSyntaxNodesForEdit(editKind, newNode, newModel, newSymbols, cancellationToken) Then Return OneOrMany(Of (ISymbol, ISymbol, EditKind)).Empty End If Return newSymbols.Select(Function(s) New ValueTuple(Of ISymbol, ISymbol, EditKind)(Nothing, s, editKind)) End If If editKind = EditKind.Update Then If Not TryGetSyntaxNodesForEdit(editKind, oldNode, oldModel, oldSymbols, cancellationToken) OrElse Not TryGetSyntaxNodesForEdit(editKind, newNode, newModel, newSymbols, cancellationToken) Then Return OneOrMany(Of (ISymbol, ISymbol, EditKind)).Empty End If If oldSymbols.Count = 1 AndAlso newSymbols.Count = 1 Then Return OneOrMany.Create((oldSymbols(0), newSymbols(0), editKind)) End If ' This only occurs when field identifiers are deleted/inserted/reordered from/to/within their variable declarator list, ' or their shared initializer is updated. The particular inserted and deleted fields will be represented by separate edits, ' but the AsNew clause of the declarator may have been updated as well, which needs to update the remaining (matching) fields. Dim builder = ArrayBuilder(Of (ISymbol, ISymbol, EditKind)).GetInstance() For Each oldSymbol In oldSymbols Dim newSymbol = newSymbols.FirstOrDefault(Function(s, o) CaseInsensitiveComparison.Equals(s.Name, o.Name), oldSymbol) If newSymbol IsNot Nothing Then builder.Add((oldSymbol, newSymbol, editKind)) End If Next Return OneOrMany.Create(builder.ToImmutableAndFree()) End If Throw ExceptionUtilities.UnexpectedValue(editKind) End Function Private Shared Function TryGetSyntaxNodesForEdit( editKind As EditKind, node As SyntaxNode, model As SemanticModel, <Out> ByRef symbols As OneOrMany(Of ISymbol), cancellationToken As CancellationToken) As Boolean Select Case node.Kind() Case SyntaxKind.ImportsStatement, SyntaxKind.NamespaceStatement, SyntaxKind.NamespaceBlock Return False Case SyntaxKind.VariableDeclarator Dim variableDeclarator = CType(node, VariableDeclaratorSyntax) If variableDeclarator.Names.Count > 1 Then symbols = OneOrMany.Create(variableDeclarator.Names.SelectAsArray(Function(n) model.GetDeclaredSymbol(n, cancellationToken))) Return True End If node = variableDeclarator.Names(0) Case SyntaxKind.FieldDeclaration If editKind = EditKind.Update Then Dim field = CType(node, FieldDeclarationSyntax) If field.Declarators.Count = 1 AndAlso field.Declarators(0).Names.Count = 1 Then node = field.Declarators(0).Names(0) Else symbols = OneOrMany.Create( (From declarator In field.Declarators From name In declarator.Names Select model.GetDeclaredSymbol(name, cancellationToken)).ToImmutableArray()) Return True End If End If End Select Dim symbol = model.GetDeclaredSymbol(node, cancellationToken) If symbol Is Nothing Then Return False End If ' Ignore partial method definition parts. ' Partial method that does not have implementation part is not emitted to metadata. ' Partial method without a definition part is a compilation error. If symbol.Kind = SymbolKind.Method AndAlso CType(symbol, IMethodSymbol).IsPartialDefinition Then Return False End If symbols = OneOrMany.Create(symbol) Return True End Function Friend Overrides Function ContainsLambda(declaration As SyntaxNode) As Boolean Return declaration.DescendantNodes().Any(AddressOf LambdaUtilities.IsLambda) End Function Friend Overrides Function IsLambda(node As SyntaxNode) As Boolean Return LambdaUtilities.IsLambda(node) End Function Friend Overrides Function IsNestedFunction(node As SyntaxNode) As Boolean Return TypeOf node Is LambdaExpressionSyntax End Function Friend Overrides Function IsLocalFunction(node As SyntaxNode) As Boolean Return False End Function Friend Overrides Function TryGetLambdaBodies(node As SyntaxNode, ByRef body1 As SyntaxNode, ByRef body2 As SyntaxNode) As Boolean Return LambdaUtilities.TryGetLambdaBodies(node, body1, body2) End Function Friend Overrides Function GetLambda(lambdaBody As SyntaxNode) As SyntaxNode Return LambdaUtilities.GetLambda(lambdaBody) End Function Protected Overrides Function GetLambdaBodyExpressionsAndStatements(lambdaBody As SyntaxNode) As IEnumerable(Of SyntaxNode) Return LambdaUtilities.GetLambdaBodyExpressionsAndStatements(lambdaBody) End Function Friend Overrides Function GetLambdaExpressionSymbol(model As SemanticModel, lambdaExpression As SyntaxNode, cancellationToken As CancellationToken) As IMethodSymbol Dim lambdaExpressionSyntax = DirectCast(lambdaExpression, LambdaExpressionSyntax) ' The semantic model only returns the lambda symbol for positions that are within the body of the lambda (not the header) Return DirectCast(model.GetEnclosingSymbol(lambdaExpressionSyntax.SubOrFunctionHeader.Span.End, cancellationToken), IMethodSymbol) End Function Friend Overrides Function GetContainingQueryExpression(node As SyntaxNode) As SyntaxNode Return node.FirstAncestorOrSelf(Of QueryExpressionSyntax) End Function Friend Overrides Function QueryClauseLambdasTypeEquivalent(oldModel As SemanticModel, oldNode As SyntaxNode, newModel As SemanticModel, newNode As SyntaxNode, cancellationToken As CancellationToken) As Boolean Select Case oldNode.Kind Case SyntaxKind.AggregateClause Dim oldInfo = oldModel.GetAggregateClauseSymbolInfo(DirectCast(oldNode, AggregateClauseSyntax), cancellationToken) Dim newInfo = newModel.GetAggregateClauseSymbolInfo(DirectCast(newNode, AggregateClauseSyntax), cancellationToken) Return MemberSignaturesEquivalent(oldInfo.Select1.Symbol, newInfo.Select1.Symbol) AndAlso MemberSignaturesEquivalent(oldInfo.Select2.Symbol, newInfo.Select2.Symbol) Case SyntaxKind.CollectionRangeVariable Dim oldInfo = oldModel.GetCollectionRangeVariableSymbolInfo(DirectCast(oldNode, CollectionRangeVariableSyntax), cancellationToken) Dim newInfo = newModel.GetCollectionRangeVariableSymbolInfo(DirectCast(newNode, CollectionRangeVariableSyntax), cancellationToken) Return MemberSignaturesEquivalent(oldInfo.AsClauseConversion.Symbol, newInfo.AsClauseConversion.Symbol) AndAlso MemberSignaturesEquivalent(oldInfo.SelectMany.Symbol, newInfo.SelectMany.Symbol) AndAlso MemberSignaturesEquivalent(oldInfo.ToQueryableCollectionConversion.Symbol, newInfo.ToQueryableCollectionConversion.Symbol) Case SyntaxKind.FunctionAggregation Dim oldInfo = oldModel.GetSymbolInfo(DirectCast(oldNode, FunctionAggregationSyntax), cancellationToken) Dim newInfo = newModel.GetSymbolInfo(DirectCast(newNode, FunctionAggregationSyntax), cancellationToken) Return MemberSignaturesEquivalent(oldInfo.Symbol, newInfo.Symbol) Case SyntaxKind.ExpressionRangeVariable Dim oldInfo = oldModel.GetSymbolInfo(DirectCast(oldNode, ExpressionRangeVariableSyntax), cancellationToken) Dim newInfo = newModel.GetSymbolInfo(DirectCast(newNode, ExpressionRangeVariableSyntax), cancellationToken) Return MemberSignaturesEquivalent(oldInfo.Symbol, newInfo.Symbol) Case SyntaxKind.AscendingOrdering, SyntaxKind.DescendingOrdering Dim oldInfo = oldModel.GetSymbolInfo(DirectCast(oldNode, OrderingSyntax), cancellationToken) Dim newInfo = newModel.GetSymbolInfo(DirectCast(newNode, OrderingSyntax), cancellationToken) Return MemberSignaturesEquivalent(oldInfo.Symbol, newInfo.Symbol) Case SyntaxKind.FromClause, SyntaxKind.WhereClause, SyntaxKind.SkipClause, SyntaxKind.TakeClause, SyntaxKind.SkipWhileClause, SyntaxKind.TakeWhileClause, SyntaxKind.GroupByClause, SyntaxKind.SimpleJoinClause, SyntaxKind.GroupJoinClause, SyntaxKind.SelectClause Dim oldInfo = oldModel.GetSymbolInfo(DirectCast(oldNode, QueryClauseSyntax), cancellationToken) Dim newInfo = newModel.GetSymbolInfo(DirectCast(newNode, QueryClauseSyntax), cancellationToken) Return MemberSignaturesEquivalent(oldInfo.Symbol, newInfo.Symbol) Case Else Return True End Select End Function Protected Overrides Sub ReportLocalFunctionsDeclarationRudeEdits(diagnostics As ArrayBuilder(Of RudeEditDiagnostic), bodyMatch As Match(Of SyntaxNode)) ' VB has no local functions so we don't have anything to report End Sub #End Region #Region "Diagnostic Info" Protected Overrides ReadOnly Property ErrorDisplayFormat As SymbolDisplayFormat Get Return SymbolDisplayFormat.VisualBasicShortErrorMessageFormat End Get End Property Protected Overrides Function TryGetDiagnosticSpan(node As SyntaxNode, editKind As EditKind) As TextSpan? Return TryGetDiagnosticSpanImpl(node, editKind) End Function Protected Overloads Shared Function GetDiagnosticSpan(node As SyntaxNode, editKind As EditKind) As TextSpan Return If(TryGetDiagnosticSpanImpl(node, editKind), node.Span) End Function Private Shared Function TryGetDiagnosticSpanImpl(node As SyntaxNode, editKind As EditKind) As TextSpan? Return TryGetDiagnosticSpanImpl(node.Kind, node, editKind) End Function Protected Overrides Function GetBodyDiagnosticSpan(node As SyntaxNode, editKind As EditKind) As TextSpan Return GetDiagnosticSpan(node, editKind) End Function ' internal for testing; kind is passed explicitly for testing as well Friend Shared Function TryGetDiagnosticSpanImpl(kind As SyntaxKind, node As SyntaxNode, editKind As EditKind) As TextSpan? Select Case kind Case SyntaxKind.CompilationUnit Return New TextSpan() Case SyntaxKind.OptionStatement, SyntaxKind.ImportsStatement Return node.Span Case SyntaxKind.NamespaceBlock Return GetDiagnosticSpan(DirectCast(node, NamespaceBlockSyntax).NamespaceStatement) Case SyntaxKind.NamespaceStatement Return GetDiagnosticSpan(DirectCast(node, NamespaceStatementSyntax)) Case SyntaxKind.ClassBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock, SyntaxKind.ModuleBlock Return GetDiagnosticSpan(DirectCast(node, TypeBlockSyntax).BlockStatement) Case SyntaxKind.ClassStatement, SyntaxKind.StructureStatement, SyntaxKind.InterfaceStatement, SyntaxKind.ModuleStatement Return GetDiagnosticSpan(DirectCast(node, TypeStatementSyntax)) Case SyntaxKind.EnumBlock Return TryGetDiagnosticSpanImpl(DirectCast(node, EnumBlockSyntax).EnumStatement, editKind) Case SyntaxKind.EnumStatement Dim enumStatement = DirectCast(node, EnumStatementSyntax) Return GetDiagnosticSpan(enumStatement.Modifiers, enumStatement.EnumKeyword, enumStatement.Identifier) Case SyntaxKind.SubBlock, SyntaxKind.FunctionBlock, SyntaxKind.OperatorBlock, SyntaxKind.ConstructorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.GetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock Return GetDiagnosticSpan(DirectCast(node, MethodBlockBaseSyntax).BlockStatement) Case SyntaxKind.EventBlock Return GetDiagnosticSpan(DirectCast(node, EventBlockSyntax).EventStatement) Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement, SyntaxKind.OperatorStatement, SyntaxKind.SubNewStatement, SyntaxKind.EventStatement, SyntaxKind.SetAccessorStatement, SyntaxKind.GetAccessorStatement, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorStatement, SyntaxKind.DeclareSubStatement, SyntaxKind.DeclareFunctionStatement, SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement Return GetDiagnosticSpan(DirectCast(node, MethodBaseSyntax)) Case SyntaxKind.PropertyBlock Return GetDiagnosticSpan(DirectCast(node, PropertyBlockSyntax).PropertyStatement) Case SyntaxKind.PropertyStatement Return GetDiagnosticSpan(DirectCast(node, PropertyStatementSyntax)) Case SyntaxKind.FieldDeclaration Dim fieldDeclaration = DirectCast(node, FieldDeclarationSyntax) Return GetDiagnosticSpan(fieldDeclaration.Modifiers, fieldDeclaration.Declarators.First, fieldDeclaration.Declarators.Last) Case SyntaxKind.VariableDeclarator, SyntaxKind.ModifiedIdentifier, SyntaxKind.EnumMemberDeclaration, SyntaxKind.TypeParameterSingleConstraintClause, SyntaxKind.TypeParameterMultipleConstraintClause, SyntaxKind.ClassConstraint, SyntaxKind.StructureConstraint, SyntaxKind.NewConstraint, SyntaxKind.TypeConstraint Return node.Span Case SyntaxKind.TypeParameter Return DirectCast(node, TypeParameterSyntax).Identifier.Span Case SyntaxKind.TypeParameterList, SyntaxKind.ParameterList, SyntaxKind.AttributeList, SyntaxKind.SimpleAsClause If editKind = EditKind.Delete Then Return TryGetDiagnosticSpanImpl(node.Parent, editKind) Else Return node.Span End If Case SyntaxKind.AttributesStatement, SyntaxKind.Attribute Return node.Span Case SyntaxKind.Parameter Dim parameter = DirectCast(node, ParameterSyntax) Return GetDiagnosticSpan(parameter.Modifiers, parameter.Identifier, parameter) Case SyntaxKind.MultiLineFunctionLambdaExpression, SyntaxKind.SingleLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression, SyntaxKind.SingleLineSubLambdaExpression Return GetDiagnosticSpan(DirectCast(node, LambdaExpressionSyntax).SubOrFunctionHeader) Case SyntaxKind.MultiLineIfBlock Dim ifStatement = DirectCast(node, MultiLineIfBlockSyntax).IfStatement Return GetDiagnosticSpan(ifStatement.IfKeyword, ifStatement.Condition, ifStatement.ThenKeyword) Case SyntaxKind.ElseIfBlock Dim elseIfStatement = DirectCast(node, ElseIfBlockSyntax).ElseIfStatement Return GetDiagnosticSpan(elseIfStatement.ElseIfKeyword, elseIfStatement.Condition, elseIfStatement.ThenKeyword) Case SyntaxKind.SingleLineIfStatement Dim ifStatement = DirectCast(node, SingleLineIfStatementSyntax) Return GetDiagnosticSpan(ifStatement.IfKeyword, ifStatement.Condition, ifStatement.ThenKeyword) Case SyntaxKind.SingleLineElseClause Return DirectCast(node, SingleLineElseClauseSyntax).ElseKeyword.Span Case SyntaxKind.TryBlock Return DirectCast(node, TryBlockSyntax).TryStatement.TryKeyword.Span Case SyntaxKind.CatchBlock Return DirectCast(node, CatchBlockSyntax).CatchStatement.CatchKeyword.Span Case SyntaxKind.FinallyBlock Return DirectCast(node, FinallyBlockSyntax).FinallyStatement.FinallyKeyword.Span Case SyntaxKind.SyncLockBlock Return DirectCast(node, SyncLockBlockSyntax).SyncLockStatement.Span Case SyntaxKind.WithBlock Return DirectCast(node, WithBlockSyntax).WithStatement.Span Case SyntaxKind.UsingBlock Return DirectCast(node, UsingBlockSyntax).UsingStatement.Span Case SyntaxKind.SimpleDoLoopBlock, SyntaxKind.DoWhileLoopBlock, SyntaxKind.DoUntilLoopBlock, SyntaxKind.DoLoopWhileBlock, SyntaxKind.DoLoopUntilBlock Return DirectCast(node, DoLoopBlockSyntax).DoStatement.Span Case SyntaxKind.WhileBlock Return DirectCast(node, WhileBlockSyntax).WhileStatement.Span Case SyntaxKind.ForEachBlock, SyntaxKind.ForBlock Return DirectCast(node, ForOrForEachBlockSyntax).ForOrForEachStatement.Span Case SyntaxKind.AwaitExpression Return DirectCast(node, AwaitExpressionSyntax).AwaitKeyword.Span Case SyntaxKind.AnonymousObjectCreationExpression Dim newWith = DirectCast(node, AnonymousObjectCreationExpressionSyntax) Return TextSpan.FromBounds(newWith.NewKeyword.Span.Start, newWith.Initializer.WithKeyword.Span.End) Case SyntaxKind.SingleLineFunctionLambdaExpression, SyntaxKind.SingleLineSubLambdaExpression, SyntaxKind.MultiLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression Return DirectCast(node, LambdaExpressionSyntax).SubOrFunctionHeader.Span Case SyntaxKind.QueryExpression Return TryGetDiagnosticSpanImpl(DirectCast(node, QueryExpressionSyntax).Clauses.First(), editKind) Case SyntaxKind.WhereClause Return DirectCast(node, WhereClauseSyntax).WhereKeyword.Span Case SyntaxKind.SelectClause Return DirectCast(node, SelectClauseSyntax).SelectKeyword.Span Case SyntaxKind.FromClause Return DirectCast(node, FromClauseSyntax).FromKeyword.Span Case SyntaxKind.AggregateClause Return DirectCast(node, AggregateClauseSyntax).AggregateKeyword.Span Case SyntaxKind.LetClause Return DirectCast(node, LetClauseSyntax).LetKeyword.Span Case SyntaxKind.SimpleJoinClause Return DirectCast(node, SimpleJoinClauseSyntax).JoinKeyword.Span Case SyntaxKind.GroupJoinClause Dim groupJoin = DirectCast(node, GroupJoinClauseSyntax) Return TextSpan.FromBounds(groupJoin.GroupKeyword.SpanStart, groupJoin.JoinKeyword.Span.End) Case SyntaxKind.GroupByClause Return DirectCast(node, GroupByClauseSyntax).GroupKeyword.Span Case SyntaxKind.FunctionAggregation Return node.Span Case SyntaxKind.CollectionRangeVariable, SyntaxKind.ExpressionRangeVariable Return TryGetDiagnosticSpanImpl(node.Parent, editKind) Case SyntaxKind.TakeWhileClause, SyntaxKind.SkipWhileClause Dim partition = DirectCast(node, PartitionWhileClauseSyntax) Return TextSpan.FromBounds(partition.SkipOrTakeKeyword.SpanStart, partition.WhileKeyword.Span.End) Case SyntaxKind.AscendingOrdering, SyntaxKind.DescendingOrdering Return node.Span Case SyntaxKind.JoinCondition Return DirectCast(node, JoinConditionSyntax).EqualsKeyword.Span Case Else Return node.Span End Select End Function Private Overloads Shared Function GetDiagnosticSpan(ifKeyword As SyntaxToken, condition As SyntaxNode, thenKeywordOpt As SyntaxToken) As TextSpan Return TextSpan.FromBounds(ifKeyword.Span.Start, If(thenKeywordOpt.RawKind <> 0, thenKeywordOpt.Span.End, condition.Span.End)) End Function Private Overloads Shared Function GetDiagnosticSpan(node As NamespaceStatementSyntax) As TextSpan Return TextSpan.FromBounds(node.NamespaceKeyword.SpanStart, node.Name.Span.End) End Function Private Overloads Shared Function GetDiagnosticSpan(node As TypeStatementSyntax) As TextSpan Return GetDiagnosticSpan(node.Modifiers, node.DeclarationKeyword, If(node.TypeParameterList, CType(node.Identifier, SyntaxNodeOrToken))) End Function Private Overloads Shared Function GetDiagnosticSpan(modifiers As SyntaxTokenList, start As SyntaxNodeOrToken, endNode As SyntaxNodeOrToken) As TextSpan Return TextSpan.FromBounds(If(modifiers.Count <> 0, modifiers.First.SpanStart, start.SpanStart), endNode.Span.End) End Function Private Overloads Shared Function GetDiagnosticSpan(header As MethodBaseSyntax) As TextSpan Dim startToken As SyntaxToken Dim endToken As SyntaxToken If header.Modifiers.Count > 0 Then startToken = header.Modifiers.First Else Select Case header.Kind Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement startToken = DirectCast(header, DelegateStatementSyntax).DelegateKeyword Case SyntaxKind.DeclareSubStatement, SyntaxKind.DeclareFunctionStatement startToken = DirectCast(header, DeclareStatementSyntax).DeclareKeyword Case Else startToken = header.DeclarationKeyword End Select End If If header.ParameterList IsNot Nothing Then endToken = header.ParameterList.CloseParenToken Else Select Case header.Kind Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement endToken = DirectCast(header, MethodStatementSyntax).Identifier Case SyntaxKind.DeclareSubStatement, SyntaxKind.DeclareFunctionStatement endToken = DirectCast(header, DeclareStatementSyntax).LibraryName.Token Case SyntaxKind.OperatorStatement endToken = DirectCast(header, OperatorStatementSyntax).OperatorToken Case SyntaxKind.SubNewStatement endToken = DirectCast(header, SubNewStatementSyntax).NewKeyword Case SyntaxKind.PropertyStatement endToken = DirectCast(header, PropertyStatementSyntax).Identifier Case SyntaxKind.EventStatement endToken = DirectCast(header, EventStatementSyntax).Identifier Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement endToken = DirectCast(header, DelegateStatementSyntax).Identifier Case SyntaxKind.SetAccessorStatement, SyntaxKind.GetAccessorStatement, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorStatement endToken = header.DeclarationKeyword Case Else Throw ExceptionUtilities.UnexpectedValue(header.Kind) End Select End If Return TextSpan.FromBounds(startToken.SpanStart, endToken.Span.End) End Function Private Overloads Shared Function GetDiagnosticSpan(lambda As LambdaHeaderSyntax) As TextSpan Dim startToken = If(lambda.Modifiers.Count <> 0, lambda.Modifiers.First, lambda.DeclarationKeyword) Dim endToken As SyntaxToken If lambda.ParameterList IsNot Nothing Then endToken = lambda.ParameterList.CloseParenToken Else endToken = lambda.DeclarationKeyword End If Return TextSpan.FromBounds(startToken.SpanStart, endToken.Span.End) End Function Friend Overrides Function GetLambdaParameterDiagnosticSpan(lambda As SyntaxNode, ordinal As Integer) As TextSpan Select Case lambda.Kind Case SyntaxKind.MultiLineFunctionLambdaExpression, SyntaxKind.SingleLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression, SyntaxKind.SingleLineSubLambdaExpression Return DirectCast(lambda, LambdaExpressionSyntax).SubOrFunctionHeader.ParameterList.Parameters(ordinal).Identifier.Span Case Else Return lambda.Span End Select End Function Friend Overrides Function GetDisplayName(symbol As INamedTypeSymbol) As String Select Case symbol.TypeKind Case TypeKind.Structure Return VBFeaturesResources.structure_ Case TypeKind.Module Return VBFeaturesResources.module_ Case Else Return MyBase.GetDisplayName(symbol) End Select End Function Friend Overrides Function GetDisplayName(symbol As IMethodSymbol) As String Select Case symbol.MethodKind Case MethodKind.StaticConstructor Return VBFeaturesResources.Shared_constructor Case Else Return MyBase.GetDisplayName(symbol) End Select End Function Friend Overrides Function GetDisplayName(symbol As IPropertySymbol) As String If symbol.IsWithEvents Then Return VBFeaturesResources.WithEvents_field End If Return MyBase.GetDisplayName(symbol) End Function Protected Overrides Function TryGetDisplayName(node As SyntaxNode, editKind As EditKind) As String Return TryGetDisplayNameImpl(node, editKind) End Function Protected Overloads Shared Function GetDisplayName(node As SyntaxNode, editKind As EditKind) As String Dim result = TryGetDisplayNameImpl(node, editKind) If result Is Nothing Then Throw ExceptionUtilities.UnexpectedValue(node.Kind) End If Return result End Function Protected Overrides Function GetBodyDisplayName(node As SyntaxNode, Optional editKind As EditKind = EditKind.Update) As String Return GetDisplayName(node, editKind) End Function Private Shared Function TryGetDisplayNameImpl(node As SyntaxNode, editKind As EditKind) As String Select Case node.Kind ' top-level Case SyntaxKind.OptionStatement Return VBFeaturesResources.option_ Case SyntaxKind.ImportsStatement Return VBFeaturesResources.import Case SyntaxKind.NamespaceBlock, SyntaxKind.NamespaceStatement Return FeaturesResources.namespace_ Case SyntaxKind.ClassBlock, SyntaxKind.ClassStatement Return FeaturesResources.class_ Case SyntaxKind.StructureBlock, SyntaxKind.StructureStatement Return VBFeaturesResources.structure_ Case SyntaxKind.InterfaceBlock, SyntaxKind.InterfaceStatement Return FeaturesResources.interface_ Case SyntaxKind.ModuleBlock, SyntaxKind.ModuleStatement Return VBFeaturesResources.module_ Case SyntaxKind.EnumBlock, SyntaxKind.EnumStatement Return FeaturesResources.enum_ Case SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement Return FeaturesResources.delegate_ Case SyntaxKind.FieldDeclaration Dim declaration = DirectCast(node, FieldDeclarationSyntax) Return If(declaration.Modifiers.Any(SyntaxKind.WithEventsKeyword), VBFeaturesResources.WithEvents_field, If(declaration.Modifiers.Any(SyntaxKind.ConstKeyword), FeaturesResources.const_field, FeaturesResources.field)) Case SyntaxKind.VariableDeclarator, SyntaxKind.ModifiedIdentifier Return TryGetDisplayNameImpl(node.Parent, editKind) Case SyntaxKind.SubBlock, SyntaxKind.FunctionBlock, SyntaxKind.SubStatement, SyntaxKind.FunctionStatement, SyntaxKind.DeclareSubStatement, SyntaxKind.DeclareFunctionStatement Return FeaturesResources.method Case SyntaxKind.OperatorBlock, SyntaxKind.OperatorStatement Return FeaturesResources.operator_ Case SyntaxKind.ConstructorBlock Return If(CType(node, ConstructorBlockSyntax).SubNewStatement.Modifiers.Any(SyntaxKind.SharedKeyword), VBFeaturesResources.Shared_constructor, FeaturesResources.constructor) Case SyntaxKind.SubNewStatement Return If(CType(node, SubNewStatementSyntax).Modifiers.Any(SyntaxKind.SharedKeyword), VBFeaturesResources.Shared_constructor, FeaturesResources.constructor) Case SyntaxKind.PropertyBlock Return FeaturesResources.property_ Case SyntaxKind.PropertyStatement Return If(node.IsParentKind(SyntaxKind.PropertyBlock), FeaturesResources.property_, FeaturesResources.auto_property) Case SyntaxKind.EventBlock, SyntaxKind.EventStatement Return FeaturesResources.event_ Case SyntaxKind.EnumMemberDeclaration Return FeaturesResources.enum_value Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorStatement Return FeaturesResources.property_accessor Case SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorStatement Return FeaturesResources.event_accessor Case SyntaxKind.TypeParameterSingleConstraintClause, SyntaxKind.TypeParameterMultipleConstraintClause, SyntaxKind.ClassConstraint, SyntaxKind.StructureConstraint, SyntaxKind.NewConstraint, SyntaxKind.TypeConstraint Return FeaturesResources.type_constraint Case SyntaxKind.SimpleAsClause Return VBFeaturesResources.as_clause Case SyntaxKind.TypeParameterList Return VBFeaturesResources.type_parameters Case SyntaxKind.TypeParameter Return FeaturesResources.type_parameter Case SyntaxKind.ParameterList Return VBFeaturesResources.parameters Case SyntaxKind.Parameter Return FeaturesResources.parameter Case SyntaxKind.AttributeList, SyntaxKind.AttributesStatement Return VBFeaturesResources.attributes Case SyntaxKind.Attribute Return FeaturesResources.attribute ' statement-level Case SyntaxKind.TryBlock Return VBFeaturesResources.Try_block Case SyntaxKind.CatchBlock Return VBFeaturesResources.Catch_clause Case SyntaxKind.FinallyBlock Return VBFeaturesResources.Finally_clause Case SyntaxKind.UsingBlock Return If(editKind = EditKind.Update, VBFeaturesResources.Using_statement, VBFeaturesResources.Using_block) Case SyntaxKind.WithBlock Return If(editKind = EditKind.Update, VBFeaturesResources.With_statement, VBFeaturesResources.With_block) Case SyntaxKind.SyncLockBlock Return If(editKind = EditKind.Update, VBFeaturesResources.SyncLock_statement, VBFeaturesResources.SyncLock_block) Case SyntaxKind.ForEachBlock Return If(editKind = EditKind.Update, VBFeaturesResources.For_Each_statement, VBFeaturesResources.For_Each_block) Case SyntaxKind.OnErrorGoToMinusOneStatement, SyntaxKind.OnErrorGoToZeroStatement, SyntaxKind.OnErrorResumeNextStatement, SyntaxKind.OnErrorGoToLabelStatement Return VBFeaturesResources.On_Error_statement Case SyntaxKind.ResumeStatement, SyntaxKind.ResumeNextStatement, SyntaxKind.ResumeLabelStatement Return VBFeaturesResources.Resume_statement Case SyntaxKind.YieldStatement Return VBFeaturesResources.Yield_statement Case SyntaxKind.AwaitExpression Return VBFeaturesResources.Await_expression Case SyntaxKind.MultiLineFunctionLambdaExpression, SyntaxKind.SingleLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression, SyntaxKind.SingleLineSubLambdaExpression, SyntaxKind.FunctionLambdaHeader, SyntaxKind.SubLambdaHeader Return VBFeaturesResources.Lambda Case SyntaxKind.WhereClause Return VBFeaturesResources.Where_clause Case SyntaxKind.SelectClause Return VBFeaturesResources.Select_clause Case SyntaxKind.FromClause Return VBFeaturesResources.From_clause Case SyntaxKind.AggregateClause Return VBFeaturesResources.Aggregate_clause Case SyntaxKind.LetClause Return VBFeaturesResources.Let_clause Case SyntaxKind.SimpleJoinClause Return VBFeaturesResources.Join_clause Case SyntaxKind.GroupJoinClause Return VBFeaturesResources.Group_Join_clause Case SyntaxKind.GroupByClause Return VBFeaturesResources.Group_By_clause Case SyntaxKind.FunctionAggregation Return VBFeaturesResources.Function_aggregation Case SyntaxKind.CollectionRangeVariable, SyntaxKind.ExpressionRangeVariable Return TryGetDisplayNameImpl(node.Parent, editKind) Case SyntaxKind.TakeWhileClause Return VBFeaturesResources.Take_While_clause Case SyntaxKind.SkipWhileClause Return VBFeaturesResources.Skip_While_clause Case SyntaxKind.AscendingOrdering, SyntaxKind.DescendingOrdering Return VBFeaturesResources.Ordering_clause Case SyntaxKind.JoinCondition Return VBFeaturesResources.Join_condition Case Else Return Nothing End Select End Function #End Region #Region "Top-level Syntactic Rude Edits" Private Structure EditClassifier Private ReadOnly _analyzer As VisualBasicEditAndContinueAnalyzer Private ReadOnly _diagnostics As ArrayBuilder(Of RudeEditDiagnostic) Private ReadOnly _match As Match(Of SyntaxNode) Private ReadOnly _oldNode As SyntaxNode Private ReadOnly _newNode As SyntaxNode Private ReadOnly _kind As EditKind Private ReadOnly _span As TextSpan? Public Sub New(analyzer As VisualBasicEditAndContinueAnalyzer, diagnostics As ArrayBuilder(Of RudeEditDiagnostic), oldNode As SyntaxNode, newNode As SyntaxNode, kind As EditKind, Optional match As Match(Of SyntaxNode) = Nothing, Optional span As TextSpan? = Nothing) _analyzer = analyzer _diagnostics = diagnostics _oldNode = oldNode _newNode = newNode _kind = kind _span = span _match = match End Sub Private Sub ReportError(kind As RudeEditKind) ReportError(kind, {GetDisplayName(If(_newNode, _oldNode), EditKind.Update)}) End Sub Private Sub ReportError(kind As RudeEditKind, args As String()) _diagnostics.Add(New RudeEditDiagnostic(kind, GetSpan(), If(_newNode, _oldNode), args)) End Sub Private Sub ReportError(kind As RudeEditKind, spanNode As SyntaxNode, displayNode As SyntaxNode) _diagnostics.Add(New RudeEditDiagnostic(kind, GetDiagnosticSpan(spanNode, _kind), displayNode, {GetDisplayName(displayNode, EditKind.Update)})) End Sub Private Function GetSpan() As TextSpan If _span.HasValue Then Return _span.Value End If If _newNode Is Nothing Then Return _analyzer.GetDeletedNodeDiagnosticSpan(_match.Matches, _oldNode) Else Return GetDiagnosticSpan(_newNode, _kind) End If End Function Public Sub ClassifyEdit() Select Case _kind Case EditKind.Delete ClassifyDelete(_oldNode) Return Case EditKind.Update ClassifyUpdate(_oldNode, _newNode) Return Case EditKind.Move ClassifyMove(_newNode) Return Case EditKind.Insert ClassifyInsert(_newNode) Return Case EditKind.Reorder ClassifyReorder(_oldNode, _newNode) Return Case Else Throw ExceptionUtilities.UnexpectedValue(_kind) End Select End Sub #Region "Move and Reorder" Private Sub ClassifyMove(newNode As SyntaxNode) Select Case newNode.Kind Case SyntaxKind.ModifiedIdentifier, SyntaxKind.VariableDeclarator ' Identifier can be moved within the same type declaration. ' Determine validity of such change in semantic analysis. Return Case Else ReportError(RudeEditKind.Move) End Select End Sub Private Sub ClassifyReorder(oldNode As SyntaxNode, newNode As SyntaxNode) Select Case newNode.Kind Case SyntaxKind.OptionStatement, SyntaxKind.ImportsStatement, SyntaxKind.AttributesStatement, SyntaxKind.NamespaceBlock, SyntaxKind.ClassBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock, SyntaxKind.ModuleBlock, SyntaxKind.EnumBlock, SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement, SyntaxKind.SubBlock, SyntaxKind.FunctionBlock, SyntaxKind.DeclareSubStatement, SyntaxKind.DeclareFunctionStatement, SyntaxKind.ConstructorBlock, SyntaxKind.OperatorBlock, SyntaxKind.PropertyBlock, SyntaxKind.EventBlock, SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock, SyntaxKind.ClassConstraint, SyntaxKind.StructureConstraint, SyntaxKind.NewConstraint, SyntaxKind.TypeConstraint, SyntaxKind.AttributeList, SyntaxKind.Attribute ' We'll ignore these edits. A general policy is to ignore edits that are only discoverable via reflection. Return Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement ' Interface methods. We could allow reordering of non-COM interface methods. Debug.Assert(oldNode.Parent.IsKind(SyntaxKind.InterfaceBlock) AndAlso newNode.Parent.IsKind(SyntaxKind.InterfaceBlock)) ReportError(RudeEditKind.Move) Return Case SyntaxKind.PropertyStatement, SyntaxKind.FieldDeclaration, SyntaxKind.EventStatement ' Maybe we could allow changing order of field declarations unless the containing type layout is sequential, ' and it's not a COM interface. ReportError(RudeEditKind.Move) Return Case SyntaxKind.EnumMemberDeclaration ' To allow this change we would need to check that values of all fields of the enum ' are preserved, or make sure we can update all method bodies that accessed those that changed. ReportError(RudeEditKind.Move) Return Case SyntaxKind.TypeParameter, SyntaxKind.Parameter ReportError(RudeEditKind.Move) Return Case SyntaxKind.ModifiedIdentifier, SyntaxKind.VariableDeclarator ' Identifier can be moved within the same type declaration. ' Determine validity of such change in semantic analysis. Return Case Else Throw ExceptionUtilities.UnexpectedValue(newNode.Kind) End Select End Sub #End Region #Region "Insert" Private Sub ClassifyInsert(node As SyntaxNode) Select Case node.Kind Case SyntaxKind.OptionStatement, SyntaxKind.NamespaceBlock ReportError(RudeEditKind.Insert) Return Case SyntaxKind.AttributesStatement ' Module/assembly attribute ReportError(RudeEditKind.Insert) Return Case SyntaxKind.Attribute ' Only module/assembly attributes are rude If node.Parent.IsParentKind(SyntaxKind.AttributesStatement) Then ReportError(RudeEditKind.Insert) End If Return Case SyntaxKind.AttributeList ' Only module/assembly attributes are rude If node.IsParentKind(SyntaxKind.AttributesStatement) Then ReportError(RudeEditKind.Insert) End If Return End Select End Sub #End Region #Region "Delete" Private Sub ClassifyDelete(oldNode As SyntaxNode) Select Case oldNode.Kind Case SyntaxKind.OptionStatement, SyntaxKind.NamespaceBlock, SyntaxKind.AttributesStatement ReportError(RudeEditKind.Delete) Return Case SyntaxKind.AttributeList ' Only module/assembly attributes are rude edits If oldNode.IsParentKind(SyntaxKind.AttributesStatement) Then ReportError(RudeEditKind.Insert) End If Return Case SyntaxKind.Attribute ' Only module/assembly attributes are rude edits If oldNode.Parent.IsParentKind(SyntaxKind.AttributesStatement) Then ReportError(RudeEditKind.Insert) End If Return End Select End Sub #End Region #Region "Update" Private Sub ClassifyUpdate(oldNode As SyntaxNode, newNode As SyntaxNode) Select Case newNode.Kind Case SyntaxKind.OptionStatement ReportError(RudeEditKind.Update) Return Case SyntaxKind.NamespaceStatement ClassifyUpdate(DirectCast(oldNode, NamespaceStatementSyntax), DirectCast(newNode, NamespaceStatementSyntax)) Return Case SyntaxKind.AttributesStatement ReportError(RudeEditKind.Update) Return Case SyntaxKind.Attribute ' Only module/assembly attributes are rude edits If newNode.Parent.IsParentKind(SyntaxKind.AttributesStatement) Then ReportError(RudeEditKind.Update) End If Return End Select End Sub Private Sub ClassifyUpdate(oldNode As NamespaceStatementSyntax, newNode As NamespaceStatementSyntax) Debug.Assert(Not SyntaxFactory.AreEquivalent(oldNode.Name, newNode.Name)) ReportError(RudeEditKind.Renamed) End Sub Public Sub ClassifyDeclarationBodyRudeUpdates(newDeclarationOrBody As SyntaxNode) For Each node In newDeclarationOrBody.DescendantNodesAndSelf() Select Case node.Kind Case SyntaxKind.AggregateClause, SyntaxKind.GroupByClause, SyntaxKind.SimpleJoinClause, SyntaxKind.GroupJoinClause ReportError(RudeEditKind.ComplexQueryExpression, node, Me._newNode) Return Case SyntaxKind.LocalDeclarationStatement Dim declaration = DirectCast(node, LocalDeclarationStatementSyntax) If declaration.Modifiers.Any(SyntaxKind.StaticKeyword) Then ReportError(RudeEditKind.UpdateStaticLocal) End If End Select Next End Sub #End Region End Structure Friend Overrides Sub ReportTopLevelSyntacticRudeEdits( diagnostics As ArrayBuilder(Of RudeEditDiagnostic), match As Match(Of SyntaxNode), edit As Edit(Of SyntaxNode), editMap As Dictionary(Of SyntaxNode, EditKind)) ' For most nodes we ignore Insert and Delete edits if their parent was also inserted or deleted, respectively. ' For ModifiedIdentifiers though we check the grandparent instead because variables can move across ' VariableDeclarators. Moving a variable from a VariableDeclarator that only has a single variable results in ' deletion of that declarator. We don't want to report that delete. Similarly for moving to a new VariableDeclarator. If edit.Kind = EditKind.Delete AndAlso edit.OldNode.IsKind(SyntaxKind.ModifiedIdentifier) AndAlso edit.OldNode.Parent.IsKind(SyntaxKind.VariableDeclarator) Then If HasEdit(editMap, edit.OldNode.Parent.Parent, EditKind.Delete) Then Return End If ElseIf edit.Kind = EditKind.Insert AndAlso edit.NewNode.IsKind(SyntaxKind.ModifiedIdentifier) AndAlso edit.NewNode.Parent.IsKind(SyntaxKind.VariableDeclarator) Then If HasEdit(editMap, edit.NewNode.Parent.Parent, EditKind.Insert) Then Return End If ElseIf HasParentEdit(editMap, edit) Then Return End If Dim classifier = New EditClassifier(Me, diagnostics, edit.OldNode, edit.NewNode, edit.Kind, match) classifier.ClassifyEdit() End Sub Friend Overrides Sub ReportMemberBodyUpdateRudeEdits(diagnostics As ArrayBuilder(Of RudeEditDiagnostic), newMember As SyntaxNode, span As TextSpan?) Dim classifier = New EditClassifier(Me, diagnostics, Nothing, newMember, EditKind.Update, span:=span) classifier.ClassifyDeclarationBodyRudeUpdates(newMember) End Sub #End Region #Region "Semantic Rude Edits" Protected Overrides Function AreHandledEventsEqual(oldMethod As IMethodSymbol, newMethod As IMethodSymbol) As Boolean Return oldMethod.HandledEvents.SequenceEqual( newMethod.HandledEvents, Function(x, y) Return x.HandlesKind = y.HandlesKind AndAlso SymbolsEquivalent(x.EventContainer, y.EventContainer) AndAlso SymbolsEquivalent(x.EventSymbol, y.EventSymbol) AndAlso SymbolsEquivalent(x.WithEventsSourceProperty, y.WithEventsSourceProperty) End Function) End Function Friend Overrides Sub ReportInsertedMemberSymbolRudeEdits(diagnostics As ArrayBuilder(Of RudeEditDiagnostic), newSymbol As ISymbol, newNode As SyntaxNode, insertingIntoExistingContainingType As Boolean) Dim kind = GetInsertedMemberSymbolRudeEditKind(newSymbol, insertingIntoExistingContainingType) If kind <> RudeEditKind.None Then diagnostics.Add(New RudeEditDiagnostic( kind, GetDiagnosticSpan(newNode, EditKind.Insert), newNode, arguments:={GetDisplayName(newNode, EditKind.Insert)})) End If End Sub Private Shared Function GetInsertedMemberSymbolRudeEditKind(newSymbol As ISymbol, insertingIntoExistingContainingType As Boolean) As RudeEditKind Select Case newSymbol.Kind Case SymbolKind.Method Dim method = DirectCast(newSymbol, IMethodSymbol) ' Inserting P/Invoke into a new or existing type is not allowed. If method.GetDllImportData() IsNot Nothing Then Return RudeEditKind.InsertDllImport End If ' Inserting method with handles clause into a new or existing type is not allowed. If Not method.HandledEvents.IsEmpty Then Return RudeEditKind.InsertHandlesClause End If Case SymbolKind.NamedType Dim type = CType(newSymbol, INamedTypeSymbol) ' Inserting module is not allowed. If type.TypeKind = TypeKind.Module Then Return RudeEditKind.Insert End If End Select ' All rude edits below only apply when inserting into an existing type (not when the type itself is inserted): If Not insertingIntoExistingContainingType Then Return RudeEditKind.None End If If newSymbol.ContainingType.Arity > 0 AndAlso newSymbol.Kind <> SymbolKind.NamedType Then Return RudeEditKind.InsertIntoGenericType End If ' Inserting virtual or interface member is not allowed. If (newSymbol.IsVirtual Or newSymbol.IsOverride Or newSymbol.IsAbstract) AndAlso newSymbol.Kind <> SymbolKind.NamedType Then Return RudeEditKind.InsertVirtual End If Select Case newSymbol.Kind Case SymbolKind.Method Dim method = DirectCast(newSymbol, IMethodSymbol) ' Inserting generic method into an existing type is not allowed. If method.Arity > 0 Then Return RudeEditKind.InsertGenericMethod End If ' Inserting operator to an existing type is not allowed. If method.MethodKind = MethodKind.Conversion OrElse method.MethodKind = MethodKind.UserDefinedOperator Then Return RudeEditKind.InsertOperator End If Return RudeEditKind.None Case SymbolKind.Field ' Inserting a field into an enum is not allowed. If newSymbol.ContainingType.TypeKind = TypeKind.Enum Then Return RudeEditKind.Insert End If Return RudeEditKind.None End Select Return RudeEditKind.None End Function #End Region #Region "Exception Handling Rude Edits" Protected Overrides Function GetExceptionHandlingAncestors(node As SyntaxNode, isNonLeaf As Boolean) As List(Of SyntaxNode) Dim result = New List(Of SyntaxNode)() While node IsNot Nothing Dim kind = node.Kind Select Case kind Case SyntaxKind.TryBlock If isNonLeaf Then result.Add(node) End If Case SyntaxKind.CatchBlock, SyntaxKind.FinallyBlock result.Add(node) Debug.Assert(node.Parent.Kind = SyntaxKind.TryBlock) node = node.Parent Case SyntaxKind.ClassBlock, SyntaxKind.StructureBlock ' stop at type declaration Exit While End Select ' stop at lambda If LambdaUtilities.IsLambda(node) Then Exit While End If node = node.Parent End While Return result End Function Friend Overrides Sub ReportEnclosingExceptionHandlingRudeEdits(diagnostics As ArrayBuilder(Of RudeEditDiagnostic), exceptionHandlingEdits As IEnumerable(Of Edit(Of SyntaxNode)), oldStatement As SyntaxNode, newStatementSpan As TextSpan) For Each edit In exceptionHandlingEdits Debug.Assert(edit.Kind <> EditKind.Update OrElse edit.OldNode.RawKind = edit.NewNode.RawKind) If edit.Kind <> EditKind.Update OrElse Not AreExceptionHandlingPartsEquivalent(edit.OldNode, edit.NewNode) Then AddAroundActiveStatementRudeDiagnostic(diagnostics, edit.OldNode, edit.NewNode, newStatementSpan) End If Next End Sub Private Shared Function AreExceptionHandlingPartsEquivalent(oldNode As SyntaxNode, newNode As SyntaxNode) As Boolean Select Case oldNode.Kind Case SyntaxKind.TryBlock Dim oldTryBlock = DirectCast(oldNode, TryBlockSyntax) Dim newTryBlock = DirectCast(newNode, TryBlockSyntax) Return SyntaxFactory.AreEquivalent(oldTryBlock.FinallyBlock, newTryBlock.FinallyBlock) AndAlso SyntaxFactory.AreEquivalent(oldTryBlock.CatchBlocks, newTryBlock.CatchBlocks) Case SyntaxKind.CatchBlock, SyntaxKind.FinallyBlock Return SyntaxFactory.AreEquivalent(oldNode, newNode) Case Else Throw ExceptionUtilities.UnexpectedValue(oldNode.Kind) End Select End Function ''' <summary> ''' An active statement (leaf or not) inside a "Catch" makes the Catch part readonly. ''' An active statement (leaf or not) inside a "Finally" makes the whole Try/Catch/Finally part read-only. ''' An active statement (non leaf) inside a "Try" makes the Catch/Finally part read-only. ''' </summary> Protected Overrides Function GetExceptionHandlingRegion(node As SyntaxNode, <Out> ByRef coversAllChildren As Boolean) As TextSpan Select Case node.Kind Case SyntaxKind.TryBlock Dim tryBlock = DirectCast(node, TryBlockSyntax) coversAllChildren = False If tryBlock.CatchBlocks.Count = 0 Then Debug.Assert(tryBlock.FinallyBlock IsNot Nothing) Return TextSpan.FromBounds(tryBlock.FinallyBlock.SpanStart, tryBlock.EndTryStatement.Span.End) End If Return TextSpan.FromBounds(tryBlock.CatchBlocks.First().SpanStart, tryBlock.EndTryStatement.Span.End) Case SyntaxKind.CatchBlock coversAllChildren = True Return node.Span Case SyntaxKind.FinallyBlock coversAllChildren = True Return DirectCast(node.Parent, TryBlockSyntax).Span Case Else Throw ExceptionUtilities.UnexpectedValue(node.Kind) End Select End Function #End Region #Region "State Machines" Friend Overrides Function IsStateMachineMethod(declaration As SyntaxNode) As Boolean Return SyntaxUtilities.IsAsyncMethodOrLambda(declaration) OrElse SyntaxUtilities.IsIteratorMethodOrLambda(declaration) End Function Protected Overrides Sub GetStateMachineInfo(body As SyntaxNode, ByRef suspensionPoints As ImmutableArray(Of SyntaxNode), ByRef kind As StateMachineKinds) ' In VB declaration and body are represented by the same node for both lambdas and methods (unlike C#) If SyntaxUtilities.IsAsyncMethodOrLambda(body) Then suspensionPoints = SyntaxUtilities.GetAwaitExpressions(body) kind = StateMachineKinds.Async ElseIf SyntaxUtilities.IsIteratorMethodOrLambda(body) Then suspensionPoints = SyntaxUtilities.GetYieldStatements(body) kind = StateMachineKinds.Iterator Else suspensionPoints = ImmutableArray(Of SyntaxNode).Empty kind = StateMachineKinds.None End If End Sub Friend Overrides Sub ReportStateMachineSuspensionPointRudeEdits(diagnostics As ArrayBuilder(Of RudeEditDiagnostic), oldNode As SyntaxNode, newNode As SyntaxNode) ' TODO: changes around suspension points (foreach, lock, using, etc.) If newNode.IsKind(SyntaxKind.AwaitExpression) Then Dim oldContainingStatementPart = FindContainingStatementPart(oldNode) Dim newContainingStatementPart = FindContainingStatementPart(newNode) ' If the old statement has spilled state and the new doesn't, the edit is ok. We'll just not use the spilled state. If Not SyntaxFactory.AreEquivalent(oldContainingStatementPart, newContainingStatementPart) AndAlso Not HasNoSpilledState(newNode, newContainingStatementPart) Then diagnostics.Add(New RudeEditDiagnostic(RudeEditKind.AwaitStatementUpdate, newContainingStatementPart.Span)) End If End If End Sub Private Shared Function FindContainingStatementPart(node As SyntaxNode) As SyntaxNode Dim statement = TryCast(node, StatementSyntax) While statement Is Nothing Select Case node.Parent.Kind() Case SyntaxKind.ForStatement, SyntaxKind.ForEachStatement, SyntaxKind.IfStatement, SyntaxKind.WhileStatement, SyntaxKind.SimpleDoStatement, SyntaxKind.SelectStatement, SyntaxKind.UsingStatement Return node End Select If LambdaUtilities.IsLambdaBodyStatementOrExpression(node) Then Return node End If node = node.Parent statement = TryCast(node, StatementSyntax) End While Return statement End Function Private Shared Function HasNoSpilledState(awaitExpression As SyntaxNode, containingStatementPart As SyntaxNode) As Boolean Debug.Assert(awaitExpression.IsKind(SyntaxKind.AwaitExpression)) ' There is nothing within the statement part surrounding the await expression. If containingStatementPart Is awaitExpression Then Return True End If Select Case containingStatementPart.Kind() Case SyntaxKind.ExpressionStatement, SyntaxKind.ReturnStatement Dim expression = GetExpressionFromStatementPart(containingStatementPart) ' Await <expr> ' Return Await <expr> If expression Is awaitExpression Then Return True End If ' <ident> = Await <expr> ' Return <ident> = Await <expr> Return IsSimpleAwaitAssignment(expression, awaitExpression) Case SyntaxKind.VariableDeclarator ' <ident> = Await <expr> in using, for, etc ' EqualsValue -> VariableDeclarator Return awaitExpression.Parent.Parent Is containingStatementPart Case SyntaxKind.LoopUntilStatement, SyntaxKind.LoopWhileStatement, SyntaxKind.DoUntilStatement, SyntaxKind.DoWhileStatement ' Until Await <expr> ' UntilClause -> LoopUntilStatement Return awaitExpression.Parent.Parent Is containingStatementPart Case SyntaxKind.LocalDeclarationStatement ' Dim <ident> = Await <expr> ' EqualsValue -> VariableDeclarator -> LocalDeclarationStatement Return awaitExpression.Parent.Parent.Parent Is containingStatementPart End Select Return IsSimpleAwaitAssignment(containingStatementPart, awaitExpression) End Function Private Shared Function GetExpressionFromStatementPart(statement As SyntaxNode) As ExpressionSyntax Select Case statement.Kind() Case SyntaxKind.ExpressionStatement Return DirectCast(statement, ExpressionStatementSyntax).Expression Case SyntaxKind.ReturnStatement Return DirectCast(statement, ReturnStatementSyntax).Expression Case Else Throw ExceptionUtilities.UnexpectedValue(statement.Kind()) End Select End Function Private Shared Function IsSimpleAwaitAssignment(node As SyntaxNode, awaitExpression As SyntaxNode) As Boolean If node.IsKind(SyntaxKind.SimpleAssignmentStatement) Then Dim assignment = DirectCast(node, AssignmentStatementSyntax) Return assignment.Left.IsKind(SyntaxKind.IdentifierName) AndAlso assignment.Right Is awaitExpression End If Return False End Function #End Region #Region "Rude Edits around Active Statement" Friend Overrides Sub ReportOtherRudeEditsAroundActiveStatement(diagnostics As ArrayBuilder(Of RudeEditDiagnostic), match As Match(Of SyntaxNode), oldActiveStatement As SyntaxNode, newActiveStatement As SyntaxNode, isNonLeaf As Boolean) Dim onErrorOrResumeStatement = FindOnErrorOrResumeStatement(match.NewRoot) If onErrorOrResumeStatement IsNot Nothing Then AddAroundActiveStatementRudeDiagnostic(diagnostics, oldActiveStatement, onErrorOrResumeStatement, newActiveStatement.Span) End If ReportRudeEditsForAncestorsDeclaringInterStatementTemps(diagnostics, match, oldActiveStatement, newActiveStatement) End Sub Private Shared Function FindOnErrorOrResumeStatement(newDeclarationOrBody As SyntaxNode) As SyntaxNode For Each node In newDeclarationOrBody.DescendantNodes(AddressOf ChildrenCompiledInBody) Select Case node.Kind Case SyntaxKind.OnErrorGoToLabelStatement, SyntaxKind.OnErrorGoToMinusOneStatement, SyntaxKind.OnErrorGoToZeroStatement, SyntaxKind.OnErrorResumeNextStatement, SyntaxKind.ResumeStatement, SyntaxKind.ResumeNextStatement, SyntaxKind.ResumeLabelStatement Return node End Select Next Return Nothing End Function Private Sub ReportRudeEditsForAncestorsDeclaringInterStatementTemps(diagnostics As ArrayBuilder(Of RudeEditDiagnostic), match As Match(Of SyntaxNode), oldActiveStatement As SyntaxNode, newActiveStatement As SyntaxNode) ' Rude Edits for Using/SyncLock/With/ForEach statements that are added/updated around an active statement. ' Although such changes are technically possible, they might lead to confusion since ' the temporary variables these statements generate won't be properly initialized. ' ' We use a simple algorithm to match each New node with its old counterpart. ' If all nodes match this algorithm Is linear, otherwise it's quadratic. ' ' Unlike exception regions matching where we use LCS, we allow reordering of the statements. ReportUnmatchedStatements(Of SyncLockBlockSyntax)(diagnostics, match, Function(node) node.IsKind(SyntaxKind.SyncLockBlock), oldActiveStatement, newActiveStatement, areEquivalent:=Function(n1, n2) AreEquivalentIgnoringLambdaBodies(n1.SyncLockStatement.Expression, n2.SyncLockStatement.Expression), areSimilar:=Nothing) ReportUnmatchedStatements(Of WithBlockSyntax)(diagnostics, match, Function(node) node.IsKind(SyntaxKind.WithBlock), oldActiveStatement, newActiveStatement, areEquivalent:=Function(n1, n2) AreEquivalentIgnoringLambdaBodies(n1.WithStatement.Expression, n2.WithStatement.Expression), areSimilar:=Nothing) ReportUnmatchedStatements(Of UsingBlockSyntax)(diagnostics, match, Function(node) node.IsKind(SyntaxKind.UsingBlock), oldActiveStatement, newActiveStatement, areEquivalent:=Function(n1, n2) AreEquivalentIgnoringLambdaBodies(n1.UsingStatement.Expression, n2.UsingStatement.Expression), areSimilar:=Nothing) ReportUnmatchedStatements(Of ForOrForEachBlockSyntax)(diagnostics, match, Function(node) node.IsKind(SyntaxKind.ForEachBlock), oldActiveStatement, newActiveStatement, areEquivalent:=Function(n1, n2) AreEquivalentIgnoringLambdaBodies(n1.ForOrForEachStatement, n2.ForOrForEachStatement), areSimilar:=Function(n1, n2) AreEquivalentIgnoringLambdaBodies(DirectCast(n1.ForOrForEachStatement, ForEachStatementSyntax).ControlVariable, DirectCast(n2.ForOrForEachStatement, ForEachStatementSyntax).ControlVariable)) End Sub #End Region End Class End Namespace
1
dotnet/roslyn
55,409
Use FixedSize API
tmat
2021-08-04T19:30:40Z
2021-08-04T21:53:46Z
e0112742bff208dd0546de45e36f7b52058a45a3
c90bf0ec986010051662c8e1fbc872c2fd86bc4e
Use FixedSize API.
./src/Compilers/CSharp/Portable/Binder/LocalBinderFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; using System; using System.Collections.Immutable; using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// The LocalBinderFactory is used to build up the map of all Binders within a method body, and the associated /// CSharpSyntaxNode. To do so it traverses all the statements, handling blocks and other /// statements that create scopes. For efficiency reasons, it does not traverse into all /// expressions. This means that blocks within lambdas and queries are not created. /// Blocks within lambdas are bound by their own LocalBinderFactory when they are /// analyzed. /// /// For reasons of lifetime management, this type is distinct from the BinderFactory /// which also creates a map from CSharpSyntaxNode to Binder. That type owns it's binders /// and that type's lifetime is that of the compilation. Therefore we do not store /// binders local to method bodies in that type's cache. /// </summary> internal sealed class LocalBinderFactory : CSharpSyntaxWalker { private readonly SmallDictionary<SyntaxNode, Binder> _map; private Symbol _containingMemberOrLambda; private Binder _enclosing; private readonly SyntaxNode _root; private void Visit(CSharpSyntaxNode syntax, Binder enclosing) { if (_enclosing == enclosing) { this.Visit(syntax); } else { Binder oldEnclosing = _enclosing; _enclosing = enclosing; this.Visit(syntax); _enclosing = oldEnclosing; } } private void VisitRankSpecifiers(TypeSyntax type, Binder enclosing) { type.VisitRankSpecifiers((rankSpecifier, args) => { foreach (var size in rankSpecifier.Sizes) { if (size.Kind() != SyntaxKind.OmittedArraySizeExpression) { args.localBinderFactory.Visit(size, args.binder); } } }, (localBinderFactory: this, binder: enclosing)); } // Currently the types of these are restricted to only be whatever the syntax parameter is, plus any LocalFunctionStatementSyntax contained within it. // This may change if the language is extended to allow iterator lambdas, in which case the lambda would also be returned. // (lambdas currently throw a diagnostic in WithLambdaParametersBinder.GetIteratorElementType when a yield is used within them) public static SmallDictionary<SyntaxNode, Binder> BuildMap( Symbol containingMemberOrLambda, SyntaxNode syntax, Binder enclosing, Action<Binder, SyntaxNode> binderUpdatedHandler = null) { var builder = new LocalBinderFactory(containingMemberOrLambda, syntax, enclosing); StatementSyntax statement; var expressionSyntax = syntax as ExpressionSyntax; if (expressionSyntax != null) { enclosing = new ExpressionVariableBinder(syntax, enclosing); if ((object)binderUpdatedHandler != null) { binderUpdatedHandler(enclosing, syntax); } builder.AddToMap(syntax, enclosing); builder.Visit(expressionSyntax, enclosing); } else if (syntax.Kind() != SyntaxKind.Block && (statement = syntax as StatementSyntax) != null) { CSharpSyntaxNode embeddedScopeDesignator; enclosing = builder.GetBinderForPossibleEmbeddedStatement(statement, enclosing, out embeddedScopeDesignator); if ((object)binderUpdatedHandler != null) { binderUpdatedHandler(enclosing, embeddedScopeDesignator); } if (embeddedScopeDesignator != null) { builder.AddToMap(embeddedScopeDesignator, enclosing); } builder.Visit(statement, enclosing); } else { if ((object)binderUpdatedHandler != null) { binderUpdatedHandler(enclosing, null); } builder.Visit((CSharpSyntaxNode)syntax, enclosing); } return builder._map; } public override void VisitCompilationUnit(CompilationUnitSyntax node) { foreach (MemberDeclarationSyntax member in node.Members) { if (member.Kind() == SyntaxKind.GlobalStatement) { Visit(member); } } } private LocalBinderFactory(Symbol containingMemberOrLambda, SyntaxNode root, Binder enclosing) { Debug.Assert((object)containingMemberOrLambda != null); Debug.Assert(containingMemberOrLambda.Kind != SymbolKind.Local && containingMemberOrLambda.Kind != SymbolKind.RangeVariable && containingMemberOrLambda.Kind != SymbolKind.Parameter); _map = new SmallDictionary<SyntaxNode, Binder>(ReferenceEqualityComparer.Instance); _containingMemberOrLambda = containingMemberOrLambda; _enclosing = enclosing; _root = root; } #region Starting points - these nodes contain statements public override void VisitMethodDeclaration(MethodDeclarationSyntax node) { Visit(node.Body); Visit(node.ExpressionBody); } public override void VisitConstructorDeclaration(ConstructorDeclarationSyntax node) { Binder enclosing = new ExpressionVariableBinder(node, _enclosing); AddToMap(node, enclosing); Visit(node.Initializer, enclosing); Visit(node.Body, enclosing); Visit(node.ExpressionBody, enclosing); } public override void VisitRecordDeclaration(RecordDeclarationSyntax node) { Debug.Assert(node.ParameterList is object); Debug.Assert(node.IsKind(SyntaxKind.RecordDeclaration)); Binder enclosing = new ExpressionVariableBinder(node, _enclosing); AddToMap(node, enclosing); Visit(node.PrimaryConstructorBaseTypeIfClass, enclosing); } public override void VisitPrimaryConstructorBaseType(PrimaryConstructorBaseTypeSyntax node) { Binder enclosing = _enclosing.WithAdditionalFlags(BinderFlags.ConstructorInitializer); AddToMap(node, enclosing); VisitConstructorInitializerArgumentList(node, node.ArgumentList, enclosing); } public override void VisitDestructorDeclaration(DestructorDeclarationSyntax node) { Visit(node.Body); Visit(node.ExpressionBody); } public override void VisitAccessorDeclaration(AccessorDeclarationSyntax node) { Visit(node.Body); Visit(node.ExpressionBody); } public override void VisitConversionOperatorDeclaration(ConversionOperatorDeclarationSyntax node) { Visit(node.Body); Visit(node.ExpressionBody); } public override void VisitOperatorDeclaration(OperatorDeclarationSyntax node) { Visit(node.Body); Visit(node.ExpressionBody); } public override void VisitSimpleLambdaExpression(SimpleLambdaExpressionSyntax node) { VisitLambdaExpression(node); } private void VisitLambdaExpression(LambdaExpressionSyntax node) { // Do not descend into a lambda unless it is a root node if (_root != node) { return; } CSharpSyntaxNode body = node.Body; if (body.Kind() == SyntaxKind.Block) { VisitBlock((BlockSyntax)body); } else { var binder = new ExpressionVariableBinder(body, _enclosing); AddToMap(body, binder); Visit(body, binder); } } public override void VisitParenthesizedLambdaExpression(ParenthesizedLambdaExpressionSyntax node) { VisitLambdaExpression(node); } public override void VisitLocalFunctionStatement(LocalFunctionStatementSyntax node) { Symbol oldMethod = _containingMemberOrLambda; Binder binder = _enclosing; LocalFunctionSymbol match = FindLocalFunction(node, _enclosing); if ((object)match != null) { _containingMemberOrLambda = match; binder = match.IsGenericMethod ? new WithMethodTypeParametersBinder(match, _enclosing) : _enclosing; binder = binder.WithUnsafeRegionIfNecessary(node.Modifiers); binder = new InMethodBinder(match, binder); } BlockSyntax blockBody = node.Body; if (blockBody != null) { Visit(blockBody, binder); } ArrowExpressionClauseSyntax arrowBody = node.ExpressionBody; if (arrowBody != null) { Visit(arrowBody, binder); } _containingMemberOrLambda = oldMethod; } private static LocalFunctionSymbol FindLocalFunction(LocalFunctionStatementSyntax node, Binder enclosing) { LocalFunctionSymbol match = null; // Don't use LookupLocalFunction because it recurses up the tree, as it // should be defined in the directly enclosing block (see note below) Binder possibleScopeBinder = enclosing; while (possibleScopeBinder != null && !possibleScopeBinder.IsLocalFunctionsScopeBinder) { possibleScopeBinder = possibleScopeBinder.Next; } if (possibleScopeBinder != null) { foreach (var candidate in possibleScopeBinder.LocalFunctions) { if (candidate.Locations[0] == node.Identifier.GetLocation()) { match = candidate; } } } return match; } public override void VisitArrowExpressionClause(ArrowExpressionClauseSyntax node) { var arrowBinder = new ExpressionVariableBinder(node, _enclosing); AddToMap(node, arrowBinder); Visit(node.Expression, arrowBinder); } public override void VisitEqualsValueClause(EqualsValueClauseSyntax node) { var valueBinder = new ExpressionVariableBinder(node, _enclosing); AddToMap(node, valueBinder); Visit(node.Value, valueBinder); } public override void VisitAttribute(AttributeSyntax node) { var attrBinder = new ExpressionVariableBinder(node, _enclosing); AddToMap(node, attrBinder); if (node.ArgumentList?.Arguments.Count > 0) { foreach (AttributeArgumentSyntax argument in node.ArgumentList.Arguments) { Visit(argument.Expression, attrBinder); } } } public override void VisitConstructorInitializer(ConstructorInitializerSyntax node) { var binder = _enclosing.WithAdditionalFlags(BinderFlags.ConstructorInitializer); AddToMap(node, binder); VisitConstructorInitializerArgumentList(node, node.ArgumentList, binder); } private void VisitConstructorInitializerArgumentList(CSharpSyntaxNode node, ArgumentListSyntax argumentList, Binder binder) { if (argumentList != null) { if (_root == node) { binder = new ExpressionVariableBinder(argumentList, binder); AddToMap(argumentList, binder); } Visit(argumentList, binder); } } public override void VisitAnonymousMethodExpression(AnonymousMethodExpressionSyntax node) { // Do not descend into a lambda unless it is a root node if (_root != node) { return; } VisitBlock(node.Block); } public override void VisitGlobalStatement(GlobalStatementSyntax node) { Visit(node.Statement); } #endregion // Top-level block has an enclosing that is not a BinderContext. All others must (so that variables can be declared). public override void VisitBlock(BlockSyntax node) { Debug.Assert((object)_containingMemberOrLambda == _enclosing.ContainingMemberOrLambda); var blockBinder = new BlockBinder(_enclosing, node); AddToMap(node, blockBinder); // Visit all the statements inside this block foreach (StatementSyntax statement in node.Statements) { Visit(statement, blockBinder); } } public override void VisitUsingStatement(UsingStatementSyntax node) { Debug.Assert((object)_containingMemberOrLambda == _enclosing.ContainingMemberOrLambda); var usingBinder = new UsingStatementBinder(_enclosing, node); AddToMap(node, usingBinder); ExpressionSyntax expressionSyntax = node.Expression; VariableDeclarationSyntax declarationSyntax = node.Declaration; Debug.Assert((expressionSyntax == null) ^ (declarationSyntax == null)); // Can't have both or neither. if (expressionSyntax != null) { Visit(expressionSyntax, usingBinder); } else { VisitRankSpecifiers(declarationSyntax.Type, usingBinder); foreach (VariableDeclaratorSyntax declarator in declarationSyntax.Variables) { Visit(declarator, usingBinder); } } VisitPossibleEmbeddedStatement(node.Statement, usingBinder); } public override void VisitWhileStatement(WhileStatementSyntax node) { Debug.Assert((object)_containingMemberOrLambda == _enclosing.ContainingMemberOrLambda); var whileBinder = new WhileBinder(_enclosing, node); AddToMap(node, whileBinder); Visit(node.Condition, whileBinder); VisitPossibleEmbeddedStatement(node.Statement, whileBinder); } public override void VisitDoStatement(DoStatementSyntax node) { Debug.Assert((object)_containingMemberOrLambda == _enclosing.ContainingMemberOrLambda); var whileBinder = new WhileBinder(_enclosing, node); AddToMap(node, whileBinder); Visit(node.Condition, whileBinder); VisitPossibleEmbeddedStatement(node.Statement, whileBinder); } public override void VisitForStatement(ForStatementSyntax node) { Debug.Assert((object)_containingMemberOrLambda == _enclosing.ContainingMemberOrLambda); Binder binder = new ForLoopBinder(_enclosing, node); AddToMap(node, binder); VariableDeclarationSyntax declaration = node.Declaration; if (declaration != null) { VisitRankSpecifiers(declaration.Type, binder); foreach (VariableDeclaratorSyntax variable in declaration.Variables) { Visit(variable, binder); } } else { foreach (ExpressionSyntax initializer in node.Initializers) { Visit(initializer, binder); } } ExpressionSyntax condition = node.Condition; if (condition != null) { binder = new ExpressionVariableBinder(condition, binder); AddToMap(condition, binder); Visit(condition, binder); } SeparatedSyntaxList<ExpressionSyntax> incrementors = node.Incrementors; if (incrementors.Count > 0) { var incrementorsBinder = new ExpressionListVariableBinder(incrementors, binder); AddToMap(incrementors.First(), incrementorsBinder); foreach (ExpressionSyntax incrementor in incrementors) { Visit(incrementor, incrementorsBinder); } } VisitPossibleEmbeddedStatement(node.Statement, binder); } private void VisitCommonForEachStatement(CommonForEachStatementSyntax node) { Debug.Assert((object)_containingMemberOrLambda == _enclosing.ContainingMemberOrLambda); var patternBinder = new ExpressionVariableBinder(node.Expression, _enclosing); AddToMap(node.Expression, patternBinder); Visit(node.Expression, patternBinder); var binder = new ForEachLoopBinder(patternBinder, node); AddToMap(node, binder); VisitPossibleEmbeddedStatement(node.Statement, binder); } public override void VisitForEachStatement(ForEachStatementSyntax node) { VisitCommonForEachStatement(node); } public override void VisitForEachVariableStatement(ForEachVariableStatementSyntax node) { VisitCommonForEachStatement(node); } public override void VisitCheckedStatement(CheckedStatementSyntax node) { Binder binder = _enclosing.WithCheckedOrUncheckedRegion(@checked: node.Kind() == SyntaxKind.CheckedStatement); AddToMap(node, binder); Visit(node.Block, binder); } public override void VisitUnsafeStatement(UnsafeStatementSyntax node) { Binder binder = _enclosing.WithAdditionalFlags(BinderFlags.UnsafeRegion); AddToMap(node, binder); Visit(node.Block, binder); // This will create the block binder for the block. } public override void VisitFixedStatement(FixedStatementSyntax node) { Debug.Assert((object)_containingMemberOrLambda == _enclosing.ContainingMemberOrLambda); var binder = new FixedStatementBinder(_enclosing, node); AddToMap(node, binder); if (node.Declaration != null) { VisitRankSpecifiers(node.Declaration.Type, binder); foreach (VariableDeclaratorSyntax declarator in node.Declaration.Variables) { Visit(declarator, binder); } } VisitPossibleEmbeddedStatement(node.Statement, binder); } public override void VisitLockStatement(LockStatementSyntax node) { var lockBinder = new LockBinder(_enclosing, node); AddToMap(node, lockBinder); Visit(node.Expression, lockBinder); StatementSyntax statement = node.Statement; Binder statementBinder = lockBinder.WithAdditionalFlags(BinderFlags.InLockBody); if (statementBinder != lockBinder) { AddToMap(statement, statementBinder); } VisitPossibleEmbeddedStatement(statement, statementBinder); } public override void VisitSwitchStatement(SwitchStatementSyntax node) { Debug.Assert((object)_containingMemberOrLambda == _enclosing.ContainingMemberOrLambda); AddToMap(node.Expression, _enclosing); Visit(node.Expression, _enclosing); var switchBinder = SwitchBinder.Create(_enclosing, node); AddToMap(node, switchBinder); foreach (SwitchSectionSyntax section in node.Sections) { Visit(section, switchBinder); } } public override void VisitSwitchSection(SwitchSectionSyntax node) { var patternBinder = new ExpressionVariableBinder(node, _enclosing); AddToMap(node, patternBinder); foreach (SwitchLabelSyntax label in node.Labels) { switch (label.Kind()) { case SyntaxKind.CasePatternSwitchLabel: { var switchLabel = (CasePatternSwitchLabelSyntax)label; Visit(switchLabel.Pattern, patternBinder); if (switchLabel.WhenClause != null) { Visit(switchLabel.WhenClause.Condition, patternBinder); } break; } case SyntaxKind.CaseSwitchLabel: { var switchLabel = (CaseSwitchLabelSyntax)label; Visit(switchLabel.Value, patternBinder); break; } } } foreach (StatementSyntax statement in node.Statements) { Visit(statement, patternBinder); } } public override void VisitSwitchExpression(SwitchExpressionSyntax node) { var switchExpressionBinder = new SwitchExpressionBinder(node, _enclosing); AddToMap(node, switchExpressionBinder); Visit(node.GoverningExpression, switchExpressionBinder); foreach (SwitchExpressionArmSyntax arm in node.Arms) { var armScopeBinder = new ExpressionVariableBinder(arm, switchExpressionBinder); var armBinder = new SwitchExpressionArmBinder(arm, armScopeBinder, switchExpressionBinder); AddToMap(arm, armBinder); Visit(arm.Pattern, armBinder); if (arm.WhenClause != null) { Visit(arm.WhenClause, armBinder); } Visit(arm.Expression, armBinder); } } public override void VisitIfStatement(IfStatementSyntax node) { Visit(node.Condition, _enclosing); VisitPossibleEmbeddedStatement(node.Statement, _enclosing); Visit(node.Else, _enclosing); } public override void VisitElseClause(ElseClauseSyntax node) { VisitPossibleEmbeddedStatement(node.Statement, _enclosing); } public override void VisitLabeledStatement(LabeledStatementSyntax node) { Visit(node.Statement, _enclosing); } public override void VisitTryStatement(TryStatementSyntax node) { if (node.Catches.Any()) { // NOTE: We're going to cheat a bit - we know that the block is definitely going // to get a map entry, so we don't need to worry about the WithAdditionalFlags // binder being dropped. That is, there's no point in adding the WithAdditionalFlags // binder to the map ourselves and having VisitBlock unconditionally overwrite it. Visit(node.Block, _enclosing.WithAdditionalFlags(BinderFlags.InTryBlockOfTryCatch)); } else { Visit(node.Block, _enclosing); } foreach (CatchClauseSyntax c in node.Catches) { Visit(c, _enclosing); } if (node.Finally != null) { Visit(node.Finally, _enclosing); } } public override void VisitCatchClause(CatchClauseSyntax node) { Debug.Assert((object)_containingMemberOrLambda == _enclosing.ContainingMemberOrLambda); var clauseBinder = new CatchClauseBinder(_enclosing, node); AddToMap(node, clauseBinder); if (node.Filter != null) { Binder filterBinder = clauseBinder.WithAdditionalFlags(BinderFlags.InCatchFilter); AddToMap(node.Filter, filterBinder); Visit(node.Filter, filterBinder); } Visit(node.Block, clauseBinder); } public override void VisitCatchFilterClause(CatchFilterClauseSyntax node) { Visit(node.FilterExpression); } public override void VisitFinallyClause(FinallyClauseSyntax node) { // NOTE: We're going to cheat a bit - we know that the block is definitely going // to get a map entry, so we don't need to worry about the WithAdditionalFlags // binder being dropped. That is, there's no point in adding the WithAdditionalFlags // binder to the map ourselves and having VisitBlock unconditionally overwrite it. // If this finally block is nested inside a catch block, we need to use a distinct // binder flag so that we can detect the nesting order for error CS074: A throw // statement with no arguments is not allowed in a finally clause that is nested inside // the nearest enclosing catch clause. var additionalFlags = BinderFlags.InFinallyBlock; if (_enclosing.Flags.Includes(BinderFlags.InCatchBlock)) { additionalFlags |= BinderFlags.InNestedFinallyBlock; } Visit(node.Block, _enclosing.WithAdditionalFlags(additionalFlags)); Binder finallyBinder; Debug.Assert(_map.TryGetValue(node.Block, out finallyBinder) && finallyBinder.Flags.Includes(BinderFlags.InFinallyBlock)); } public override void VisitYieldStatement(YieldStatementSyntax node) { if (node.Expression != null) { Visit(node.Expression, _enclosing); } } public override void VisitExpressionStatement(ExpressionStatementSyntax node) { Visit(node.Expression, _enclosing); } public override void VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node) { VisitRankSpecifiers(node.Declaration.Type, _enclosing); foreach (VariableDeclaratorSyntax decl in node.Declaration.Variables) { Visit(decl); } } public override void VisitVariableDeclarator(VariableDeclaratorSyntax node) { Visit(node.ArgumentList); Visit(node.Initializer?.Value); } public override void VisitReturnStatement(ReturnStatementSyntax node) { if (node.Expression != null) { Visit(node.Expression, _enclosing); } } public override void VisitThrowStatement(ThrowStatementSyntax node) { if (node.Expression != null) { Visit(node.Expression, _enclosing); } } public override void VisitBinaryExpression(BinaryExpressionSyntax node) { // The binary operators (except ??) are left-associative, and expressions of the form // a + b + c + d .... are relatively common in machine-generated code. The parser can handle // creating a deep-on-the-left syntax tree no problem, and then we promptly blow the stack. // For the purpose of creating binders, the order, in which we visit expressions, is not // significant. while (true) { Visit(node.Right); var binOp = node.Left as BinaryExpressionSyntax; if (binOp == null) { Visit(node.Left); break; } node = binOp; } } public override void DefaultVisit(SyntaxNode node) { // We should only get here for statements that don't introduce new scopes. // Given pattern variables, they must have no subexpressions either. // It is fine to get here for non-statements. base.DefaultVisit(node); } private void AddToMap(SyntaxNode node, Binder binder) { // If this ever breaks, make sure that all callers of // CanHaveAssociatedLocalBinder are in sync. Debug.Assert(node.CanHaveAssociatedLocalBinder() || (node == _root && node is ExpressionSyntax)); // Cleverness: for some nodes (e.g. lock), we want to specify a binder flag that // applies to the embedded statement, but not to the entire node. Since the // embedded statement may or may not have its own binder, we need a way to ensure // that the flag is set regardless. We accomplish this by adding a binder for // the embedded statement immediately, and then overwriting it with one constructed // in the usual way, if there is such a binder. That's why we're using update, // rather than add, semantics. Binder existing; // Note that a lock statement has two outer binders (a second one for pattern variable scope) Debug.Assert(!_map.TryGetValue(node, out existing) || existing == binder || existing == binder.Next || existing == binder.Next?.Next); _map[node] = binder; } /// <summary> /// Some statements by default do not introduce its own scope for locals. /// For example: Expression Statement, Return Statement, etc. However, /// when a statement like that is an embedded statement (like IfStatementSyntax.Statement), /// then it should introduce a scope for locals declared within it. /// Here we are detecting such statements and creating a binder that should own the scope. /// </summary> private Binder GetBinderForPossibleEmbeddedStatement(StatementSyntax statement, Binder enclosing, out CSharpSyntaxNode embeddedScopeDesignator) { switch (statement.Kind()) { case SyntaxKind.LocalDeclarationStatement: case SyntaxKind.LabeledStatement: case SyntaxKind.LocalFunctionStatement: // It is an error to have a declaration or a label in an embedded statement, // but we still want to bind it. case SyntaxKind.ExpressionStatement: case SyntaxKind.LockStatement: case SyntaxKind.IfStatement: case SyntaxKind.YieldReturnStatement: case SyntaxKind.ReturnStatement: case SyntaxKind.ThrowStatement: Debug.Assert((object)_containingMemberOrLambda == enclosing.ContainingMemberOrLambda); embeddedScopeDesignator = statement; return new EmbeddedStatementBinder(enclosing, statement); case SyntaxKind.SwitchStatement: Debug.Assert((object)_containingMemberOrLambda == enclosing.ContainingMemberOrLambda); var switchStatement = (SwitchStatementSyntax)statement; embeddedScopeDesignator = switchStatement.Expression; return new ExpressionVariableBinder(switchStatement.Expression, enclosing); default: embeddedScopeDesignator = null; return enclosing; } } private void VisitPossibleEmbeddedStatement(StatementSyntax statement, Binder enclosing) { if (statement != null) { CSharpSyntaxNode embeddedScopeDesignator; // Some statements by default do not introduce its own scope for locals. // For example: Expression Statement, Return Statement, etc. However, // when a statement like that is an embedded statement (like IfStatementSyntax.Statement), // then it should introduce a scope for locals declared within it. Here we are detecting // such statements and creating a binder that should own the scope. enclosing = GetBinderForPossibleEmbeddedStatement(statement, enclosing, out embeddedScopeDesignator); if (embeddedScopeDesignator != null) { AddToMap(embeddedScopeDesignator, enclosing); } Visit(statement, enclosing); } } public override void VisitQueryExpression(QueryExpressionSyntax node) { Visit(node.FromClause.Expression); Visit(node.Body); } public override void VisitQueryBody(QueryBodySyntax node) { foreach (QueryClauseSyntax clause in node.Clauses) { if (clause.Kind() == SyntaxKind.JoinClause) { Visit(((JoinClauseSyntax)clause).InExpression); } } Visit(node.Continuation); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; using System; using System.Collections.Immutable; using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// The LocalBinderFactory is used to build up the map of all Binders within a method body, and the associated /// CSharpSyntaxNode. To do so it traverses all the statements, handling blocks and other /// statements that create scopes. For efficiency reasons, it does not traverse into all /// expressions. This means that blocks within lambdas and queries are not created. /// Blocks within lambdas are bound by their own LocalBinderFactory when they are /// analyzed. /// /// For reasons of lifetime management, this type is distinct from the BinderFactory /// which also creates a map from CSharpSyntaxNode to Binder. That type owns it's binders /// and that type's lifetime is that of the compilation. Therefore we do not store /// binders local to method bodies in that type's cache. /// </summary> internal sealed class LocalBinderFactory : CSharpSyntaxWalker { private readonly SmallDictionary<SyntaxNode, Binder> _map; private Symbol _containingMemberOrLambda; private Binder _enclosing; private readonly SyntaxNode _root; private void Visit(CSharpSyntaxNode syntax, Binder enclosing) { if (_enclosing == enclosing) { this.Visit(syntax); } else { Binder oldEnclosing = _enclosing; _enclosing = enclosing; this.Visit(syntax); _enclosing = oldEnclosing; } } private void VisitRankSpecifiers(TypeSyntax type, Binder enclosing) { type.VisitRankSpecifiers((rankSpecifier, args) => { foreach (var size in rankSpecifier.Sizes) { if (size.Kind() != SyntaxKind.OmittedArraySizeExpression) { args.localBinderFactory.Visit(size, args.binder); } } }, (localBinderFactory: this, binder: enclosing)); } // Currently the types of these are restricted to only be whatever the syntax parameter is, plus any LocalFunctionStatementSyntax contained within it. // This may change if the language is extended to allow iterator lambdas, in which case the lambda would also be returned. // (lambdas currently throw a diagnostic in WithLambdaParametersBinder.GetIteratorElementType when a yield is used within them) public static SmallDictionary<SyntaxNode, Binder> BuildMap( Symbol containingMemberOrLambda, SyntaxNode syntax, Binder enclosing, Action<Binder, SyntaxNode> binderUpdatedHandler = null) { var builder = new LocalBinderFactory(containingMemberOrLambda, syntax, enclosing); StatementSyntax statement; var expressionSyntax = syntax as ExpressionSyntax; if (expressionSyntax != null) { enclosing = new ExpressionVariableBinder(syntax, enclosing); if ((object)binderUpdatedHandler != null) { binderUpdatedHandler(enclosing, syntax); } builder.AddToMap(syntax, enclosing); builder.Visit(expressionSyntax, enclosing); } else if (syntax.Kind() != SyntaxKind.Block && (statement = syntax as StatementSyntax) != null) { CSharpSyntaxNode embeddedScopeDesignator; enclosing = builder.GetBinderForPossibleEmbeddedStatement(statement, enclosing, out embeddedScopeDesignator); if ((object)binderUpdatedHandler != null) { binderUpdatedHandler(enclosing, embeddedScopeDesignator); } if (embeddedScopeDesignator != null) { builder.AddToMap(embeddedScopeDesignator, enclosing); } builder.Visit(statement, enclosing); } else { if ((object)binderUpdatedHandler != null) { binderUpdatedHandler(enclosing, null); } builder.Visit((CSharpSyntaxNode)syntax, enclosing); } return builder._map; } public override void VisitCompilationUnit(CompilationUnitSyntax node) { foreach (MemberDeclarationSyntax member in node.Members) { if (member.Kind() == SyntaxKind.GlobalStatement) { Visit(member); } } } private LocalBinderFactory(Symbol containingMemberOrLambda, SyntaxNode root, Binder enclosing) { Debug.Assert((object)containingMemberOrLambda != null); Debug.Assert(containingMemberOrLambda.Kind != SymbolKind.Local && containingMemberOrLambda.Kind != SymbolKind.RangeVariable && containingMemberOrLambda.Kind != SymbolKind.Parameter); _map = new SmallDictionary<SyntaxNode, Binder>(ReferenceEqualityComparer.Instance); _containingMemberOrLambda = containingMemberOrLambda; _enclosing = enclosing; _root = root; } #region Starting points - these nodes contain statements public override void VisitMethodDeclaration(MethodDeclarationSyntax node) { Visit(node.Body); Visit(node.ExpressionBody); } public override void VisitConstructorDeclaration(ConstructorDeclarationSyntax node) { Binder enclosing = new ExpressionVariableBinder(node, _enclosing); AddToMap(node, enclosing); Visit(node.Initializer, enclosing); Visit(node.Body, enclosing); Visit(node.ExpressionBody, enclosing); } public override void VisitRecordDeclaration(RecordDeclarationSyntax node) { Debug.Assert(node.ParameterList is object); Debug.Assert(node.IsKind(SyntaxKind.RecordDeclaration)); Binder enclosing = new ExpressionVariableBinder(node, _enclosing); AddToMap(node, enclosing); Visit(node.PrimaryConstructorBaseTypeIfClass, enclosing); } public override void VisitPrimaryConstructorBaseType(PrimaryConstructorBaseTypeSyntax node) { Binder enclosing = _enclosing.WithAdditionalFlags(BinderFlags.ConstructorInitializer); AddToMap(node, enclosing); VisitConstructorInitializerArgumentList(node, node.ArgumentList, enclosing); } public override void VisitDestructorDeclaration(DestructorDeclarationSyntax node) { Visit(node.Body); Visit(node.ExpressionBody); } public override void VisitAccessorDeclaration(AccessorDeclarationSyntax node) { Visit(node.Body); Visit(node.ExpressionBody); } public override void VisitConversionOperatorDeclaration(ConversionOperatorDeclarationSyntax node) { Visit(node.Body); Visit(node.ExpressionBody); } public override void VisitOperatorDeclaration(OperatorDeclarationSyntax node) { Visit(node.Body); Visit(node.ExpressionBody); } public override void VisitSimpleLambdaExpression(SimpleLambdaExpressionSyntax node) { VisitLambdaExpression(node); } private void VisitLambdaExpression(LambdaExpressionSyntax node) { // Do not descend into a lambda unless it is a root node if (_root != node) { return; } CSharpSyntaxNode body = node.Body; if (body.Kind() == SyntaxKind.Block) { VisitBlock((BlockSyntax)body); } else { var binder = new ExpressionVariableBinder(body, _enclosing); AddToMap(body, binder); Visit(body, binder); } } public override void VisitParenthesizedLambdaExpression(ParenthesizedLambdaExpressionSyntax node) { VisitLambdaExpression(node); } public override void VisitLocalFunctionStatement(LocalFunctionStatementSyntax node) { Symbol oldMethod = _containingMemberOrLambda; Binder binder = _enclosing; LocalFunctionSymbol match = FindLocalFunction(node, _enclosing); if ((object)match != null) { _containingMemberOrLambda = match; binder = match.IsGenericMethod ? new WithMethodTypeParametersBinder(match, _enclosing) : _enclosing; binder = binder.WithUnsafeRegionIfNecessary(node.Modifiers); binder = new InMethodBinder(match, binder); } BlockSyntax blockBody = node.Body; if (blockBody != null) { Visit(blockBody, binder); } ArrowExpressionClauseSyntax arrowBody = node.ExpressionBody; if (arrowBody != null) { Visit(arrowBody, binder); } _containingMemberOrLambda = oldMethod; } private static LocalFunctionSymbol FindLocalFunction(LocalFunctionStatementSyntax node, Binder enclosing) { LocalFunctionSymbol match = null; // Don't use LookupLocalFunction because it recurses up the tree, as it // should be defined in the directly enclosing block (see note below) Binder possibleScopeBinder = enclosing; while (possibleScopeBinder != null && !possibleScopeBinder.IsLocalFunctionsScopeBinder) { possibleScopeBinder = possibleScopeBinder.Next; } if (possibleScopeBinder != null) { foreach (var candidate in possibleScopeBinder.LocalFunctions) { if (candidate.Locations[0] == node.Identifier.GetLocation()) { match = candidate; } } } return match; } public override void VisitArrowExpressionClause(ArrowExpressionClauseSyntax node) { var arrowBinder = new ExpressionVariableBinder(node, _enclosing); AddToMap(node, arrowBinder); Visit(node.Expression, arrowBinder); } public override void VisitEqualsValueClause(EqualsValueClauseSyntax node) { var valueBinder = new ExpressionVariableBinder(node, _enclosing); AddToMap(node, valueBinder); Visit(node.Value, valueBinder); } public override void VisitAttribute(AttributeSyntax node) { var attrBinder = new ExpressionVariableBinder(node, _enclosing); AddToMap(node, attrBinder); if (node.ArgumentList?.Arguments.Count > 0) { foreach (AttributeArgumentSyntax argument in node.ArgumentList.Arguments) { Visit(argument.Expression, attrBinder); } } } public override void VisitConstructorInitializer(ConstructorInitializerSyntax node) { var binder = _enclosing.WithAdditionalFlags(BinderFlags.ConstructorInitializer); AddToMap(node, binder); VisitConstructorInitializerArgumentList(node, node.ArgumentList, binder); } private void VisitConstructorInitializerArgumentList(CSharpSyntaxNode node, ArgumentListSyntax argumentList, Binder binder) { if (argumentList != null) { if (_root == node) { binder = new ExpressionVariableBinder(argumentList, binder); AddToMap(argumentList, binder); } Visit(argumentList, binder); } } public override void VisitAnonymousMethodExpression(AnonymousMethodExpressionSyntax node) { // Do not descend into a lambda unless it is a root node if (_root != node) { return; } VisitBlock(node.Block); } public override void VisitGlobalStatement(GlobalStatementSyntax node) { Visit(node.Statement); } #endregion // Top-level block has an enclosing that is not a BinderContext. All others must (so that variables can be declared). public override void VisitBlock(BlockSyntax node) { Debug.Assert((object)_containingMemberOrLambda == _enclosing.ContainingMemberOrLambda); var blockBinder = new BlockBinder(_enclosing, node); AddToMap(node, blockBinder); // Visit all the statements inside this block foreach (StatementSyntax statement in node.Statements) { Visit(statement, blockBinder); } } public override void VisitUsingStatement(UsingStatementSyntax node) { Debug.Assert((object)_containingMemberOrLambda == _enclosing.ContainingMemberOrLambda); var usingBinder = new UsingStatementBinder(_enclosing, node); AddToMap(node, usingBinder); ExpressionSyntax expressionSyntax = node.Expression; VariableDeclarationSyntax declarationSyntax = node.Declaration; Debug.Assert((expressionSyntax == null) ^ (declarationSyntax == null)); // Can't have both or neither. if (expressionSyntax != null) { Visit(expressionSyntax, usingBinder); } else { VisitRankSpecifiers(declarationSyntax.Type, usingBinder); foreach (VariableDeclaratorSyntax declarator in declarationSyntax.Variables) { Visit(declarator, usingBinder); } } VisitPossibleEmbeddedStatement(node.Statement, usingBinder); } public override void VisitWhileStatement(WhileStatementSyntax node) { Debug.Assert((object)_containingMemberOrLambda == _enclosing.ContainingMemberOrLambda); var whileBinder = new WhileBinder(_enclosing, node); AddToMap(node, whileBinder); Visit(node.Condition, whileBinder); VisitPossibleEmbeddedStatement(node.Statement, whileBinder); } public override void VisitDoStatement(DoStatementSyntax node) { Debug.Assert((object)_containingMemberOrLambda == _enclosing.ContainingMemberOrLambda); var whileBinder = new WhileBinder(_enclosing, node); AddToMap(node, whileBinder); Visit(node.Condition, whileBinder); VisitPossibleEmbeddedStatement(node.Statement, whileBinder); } public override void VisitForStatement(ForStatementSyntax node) { Debug.Assert((object)_containingMemberOrLambda == _enclosing.ContainingMemberOrLambda); Binder binder = new ForLoopBinder(_enclosing, node); AddToMap(node, binder); VariableDeclarationSyntax declaration = node.Declaration; if (declaration != null) { VisitRankSpecifiers(declaration.Type, binder); foreach (VariableDeclaratorSyntax variable in declaration.Variables) { Visit(variable, binder); } } else { foreach (ExpressionSyntax initializer in node.Initializers) { Visit(initializer, binder); } } ExpressionSyntax condition = node.Condition; if (condition != null) { binder = new ExpressionVariableBinder(condition, binder); AddToMap(condition, binder); Visit(condition, binder); } SeparatedSyntaxList<ExpressionSyntax> incrementors = node.Incrementors; if (incrementors.Count > 0) { var incrementorsBinder = new ExpressionListVariableBinder(incrementors, binder); AddToMap(incrementors.First(), incrementorsBinder); foreach (ExpressionSyntax incrementor in incrementors) { Visit(incrementor, incrementorsBinder); } } VisitPossibleEmbeddedStatement(node.Statement, binder); } private void VisitCommonForEachStatement(CommonForEachStatementSyntax node) { Debug.Assert((object)_containingMemberOrLambda == _enclosing.ContainingMemberOrLambda); var patternBinder = new ExpressionVariableBinder(node.Expression, _enclosing); AddToMap(node.Expression, patternBinder); Visit(node.Expression, patternBinder); var binder = new ForEachLoopBinder(patternBinder, node); AddToMap(node, binder); VisitPossibleEmbeddedStatement(node.Statement, binder); } public override void VisitForEachStatement(ForEachStatementSyntax node) { VisitCommonForEachStatement(node); } public override void VisitForEachVariableStatement(ForEachVariableStatementSyntax node) { VisitCommonForEachStatement(node); } public override void VisitCheckedStatement(CheckedStatementSyntax node) { Binder binder = _enclosing.WithCheckedOrUncheckedRegion(@checked: node.Kind() == SyntaxKind.CheckedStatement); AddToMap(node, binder); Visit(node.Block, binder); } public override void VisitUnsafeStatement(UnsafeStatementSyntax node) { Binder binder = _enclosing.WithAdditionalFlags(BinderFlags.UnsafeRegion); AddToMap(node, binder); Visit(node.Block, binder); // This will create the block binder for the block. } public override void VisitFixedStatement(FixedStatementSyntax node) { Debug.Assert((object)_containingMemberOrLambda == _enclosing.ContainingMemberOrLambda); var binder = new FixedStatementBinder(_enclosing, node); AddToMap(node, binder); if (node.Declaration != null) { VisitRankSpecifiers(node.Declaration.Type, binder); foreach (VariableDeclaratorSyntax declarator in node.Declaration.Variables) { Visit(declarator, binder); } } VisitPossibleEmbeddedStatement(node.Statement, binder); } public override void VisitLockStatement(LockStatementSyntax node) { var lockBinder = new LockBinder(_enclosing, node); AddToMap(node, lockBinder); Visit(node.Expression, lockBinder); StatementSyntax statement = node.Statement; Binder statementBinder = lockBinder.WithAdditionalFlags(BinderFlags.InLockBody); if (statementBinder != lockBinder) { AddToMap(statement, statementBinder); } VisitPossibleEmbeddedStatement(statement, statementBinder); } public override void VisitSwitchStatement(SwitchStatementSyntax node) { Debug.Assert((object)_containingMemberOrLambda == _enclosing.ContainingMemberOrLambda); AddToMap(node.Expression, _enclosing); Visit(node.Expression, _enclosing); var switchBinder = SwitchBinder.Create(_enclosing, node); AddToMap(node, switchBinder); foreach (SwitchSectionSyntax section in node.Sections) { Visit(section, switchBinder); } } public override void VisitSwitchSection(SwitchSectionSyntax node) { var patternBinder = new ExpressionVariableBinder(node, _enclosing); AddToMap(node, patternBinder); foreach (SwitchLabelSyntax label in node.Labels) { switch (label.Kind()) { case SyntaxKind.CasePatternSwitchLabel: { var switchLabel = (CasePatternSwitchLabelSyntax)label; Visit(switchLabel.Pattern, patternBinder); if (switchLabel.WhenClause != null) { Visit(switchLabel.WhenClause.Condition, patternBinder); } break; } case SyntaxKind.CaseSwitchLabel: { var switchLabel = (CaseSwitchLabelSyntax)label; Visit(switchLabel.Value, patternBinder); break; } } } foreach (StatementSyntax statement in node.Statements) { Visit(statement, patternBinder); } } public override void VisitSwitchExpression(SwitchExpressionSyntax node) { var switchExpressionBinder = new SwitchExpressionBinder(node, _enclosing); AddToMap(node, switchExpressionBinder); Visit(node.GoverningExpression, switchExpressionBinder); foreach (SwitchExpressionArmSyntax arm in node.Arms) { var armScopeBinder = new ExpressionVariableBinder(arm, switchExpressionBinder); var armBinder = new SwitchExpressionArmBinder(arm, armScopeBinder, switchExpressionBinder); AddToMap(arm, armBinder); Visit(arm.Pattern, armBinder); if (arm.WhenClause != null) { Visit(arm.WhenClause, armBinder); } Visit(arm.Expression, armBinder); } } public override void VisitIfStatement(IfStatementSyntax node) { Visit(node.Condition, _enclosing); VisitPossibleEmbeddedStatement(node.Statement, _enclosing); Visit(node.Else, _enclosing); } public override void VisitElseClause(ElseClauseSyntax node) { VisitPossibleEmbeddedStatement(node.Statement, _enclosing); } public override void VisitLabeledStatement(LabeledStatementSyntax node) { Visit(node.Statement, _enclosing); } public override void VisitTryStatement(TryStatementSyntax node) { if (node.Catches.Any()) { // NOTE: We're going to cheat a bit - we know that the block is definitely going // to get a map entry, so we don't need to worry about the WithAdditionalFlags // binder being dropped. That is, there's no point in adding the WithAdditionalFlags // binder to the map ourselves and having VisitBlock unconditionally overwrite it. Visit(node.Block, _enclosing.WithAdditionalFlags(BinderFlags.InTryBlockOfTryCatch)); } else { Visit(node.Block, _enclosing); } foreach (CatchClauseSyntax c in node.Catches) { Visit(c, _enclosing); } if (node.Finally != null) { Visit(node.Finally, _enclosing); } } public override void VisitCatchClause(CatchClauseSyntax node) { Debug.Assert((object)_containingMemberOrLambda == _enclosing.ContainingMemberOrLambda); var clauseBinder = new CatchClauseBinder(_enclosing, node); AddToMap(node, clauseBinder); if (node.Filter != null) { Binder filterBinder = clauseBinder.WithAdditionalFlags(BinderFlags.InCatchFilter); AddToMap(node.Filter, filterBinder); Visit(node.Filter, filterBinder); } Visit(node.Block, clauseBinder); } public override void VisitCatchFilterClause(CatchFilterClauseSyntax node) { Visit(node.FilterExpression); } public override void VisitFinallyClause(FinallyClauseSyntax node) { // NOTE: We're going to cheat a bit - we know that the block is definitely going // to get a map entry, so we don't need to worry about the WithAdditionalFlags // binder being dropped. That is, there's no point in adding the WithAdditionalFlags // binder to the map ourselves and having VisitBlock unconditionally overwrite it. // If this finally block is nested inside a catch block, we need to use a distinct // binder flag so that we can detect the nesting order for error CS074: A throw // statement with no arguments is not allowed in a finally clause that is nested inside // the nearest enclosing catch clause. var additionalFlags = BinderFlags.InFinallyBlock; if (_enclosing.Flags.Includes(BinderFlags.InCatchBlock)) { additionalFlags |= BinderFlags.InNestedFinallyBlock; } Visit(node.Block, _enclosing.WithAdditionalFlags(additionalFlags)); Binder finallyBinder; Debug.Assert(_map.TryGetValue(node.Block, out finallyBinder) && finallyBinder.Flags.Includes(BinderFlags.InFinallyBlock)); } public override void VisitYieldStatement(YieldStatementSyntax node) { if (node.Expression != null) { Visit(node.Expression, _enclosing); } } public override void VisitExpressionStatement(ExpressionStatementSyntax node) { Visit(node.Expression, _enclosing); } public override void VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node) { VisitRankSpecifiers(node.Declaration.Type, _enclosing); foreach (VariableDeclaratorSyntax decl in node.Declaration.Variables) { Visit(decl); } } public override void VisitVariableDeclarator(VariableDeclaratorSyntax node) { Visit(node.ArgumentList); Visit(node.Initializer?.Value); } public override void VisitReturnStatement(ReturnStatementSyntax node) { if (node.Expression != null) { Visit(node.Expression, _enclosing); } } public override void VisitThrowStatement(ThrowStatementSyntax node) { if (node.Expression != null) { Visit(node.Expression, _enclosing); } } public override void VisitBinaryExpression(BinaryExpressionSyntax node) { // The binary operators (except ??) are left-associative, and expressions of the form // a + b + c + d .... are relatively common in machine-generated code. The parser can handle // creating a deep-on-the-left syntax tree no problem, and then we promptly blow the stack. // For the purpose of creating binders, the order, in which we visit expressions, is not // significant. while (true) { Visit(node.Right); var binOp = node.Left as BinaryExpressionSyntax; if (binOp == null) { Visit(node.Left); break; } node = binOp; } } public override void DefaultVisit(SyntaxNode node) { // We should only get here for statements that don't introduce new scopes. // Given pattern variables, they must have no subexpressions either. // It is fine to get here for non-statements. base.DefaultVisit(node); } private void AddToMap(SyntaxNode node, Binder binder) { // If this ever breaks, make sure that all callers of // CanHaveAssociatedLocalBinder are in sync. Debug.Assert(node.CanHaveAssociatedLocalBinder() || (node == _root && node is ExpressionSyntax)); // Cleverness: for some nodes (e.g. lock), we want to specify a binder flag that // applies to the embedded statement, but not to the entire node. Since the // embedded statement may or may not have its own binder, we need a way to ensure // that the flag is set regardless. We accomplish this by adding a binder for // the embedded statement immediately, and then overwriting it with one constructed // in the usual way, if there is such a binder. That's why we're using update, // rather than add, semantics. Binder existing; // Note that a lock statement has two outer binders (a second one for pattern variable scope) Debug.Assert(!_map.TryGetValue(node, out existing) || existing == binder || existing == binder.Next || existing == binder.Next?.Next); _map[node] = binder; } /// <summary> /// Some statements by default do not introduce its own scope for locals. /// For example: Expression Statement, Return Statement, etc. However, /// when a statement like that is an embedded statement (like IfStatementSyntax.Statement), /// then it should introduce a scope for locals declared within it. /// Here we are detecting such statements and creating a binder that should own the scope. /// </summary> private Binder GetBinderForPossibleEmbeddedStatement(StatementSyntax statement, Binder enclosing, out CSharpSyntaxNode embeddedScopeDesignator) { switch (statement.Kind()) { case SyntaxKind.LocalDeclarationStatement: case SyntaxKind.LabeledStatement: case SyntaxKind.LocalFunctionStatement: // It is an error to have a declaration or a label in an embedded statement, // but we still want to bind it. case SyntaxKind.ExpressionStatement: case SyntaxKind.LockStatement: case SyntaxKind.IfStatement: case SyntaxKind.YieldReturnStatement: case SyntaxKind.ReturnStatement: case SyntaxKind.ThrowStatement: Debug.Assert((object)_containingMemberOrLambda == enclosing.ContainingMemberOrLambda); embeddedScopeDesignator = statement; return new EmbeddedStatementBinder(enclosing, statement); case SyntaxKind.SwitchStatement: Debug.Assert((object)_containingMemberOrLambda == enclosing.ContainingMemberOrLambda); var switchStatement = (SwitchStatementSyntax)statement; embeddedScopeDesignator = switchStatement.Expression; return new ExpressionVariableBinder(switchStatement.Expression, enclosing); default: embeddedScopeDesignator = null; return enclosing; } } private void VisitPossibleEmbeddedStatement(StatementSyntax statement, Binder enclosing) { if (statement != null) { CSharpSyntaxNode embeddedScopeDesignator; // Some statements by default do not introduce its own scope for locals. // For example: Expression Statement, Return Statement, etc. However, // when a statement like that is an embedded statement (like IfStatementSyntax.Statement), // then it should introduce a scope for locals declared within it. Here we are detecting // such statements and creating a binder that should own the scope. enclosing = GetBinderForPossibleEmbeddedStatement(statement, enclosing, out embeddedScopeDesignator); if (embeddedScopeDesignator != null) { AddToMap(embeddedScopeDesignator, enclosing); } Visit(statement, enclosing); } } public override void VisitQueryExpression(QueryExpressionSyntax node) { Visit(node.FromClause.Expression); Visit(node.Body); } public override void VisitQueryBody(QueryBodySyntax node) { foreach (QueryClauseSyntax clause in node.Clauses) { if (clause.Kind() == SyntaxKind.JoinClause) { Visit(((JoinClauseSyntax)clause).InExpression); } } Visit(node.Continuation); } } }
-1
dotnet/roslyn
55,409
Use FixedSize API
tmat
2021-08-04T19:30:40Z
2021-08-04T21:53:46Z
e0112742bff208dd0546de45e36f7b52058a45a3
c90bf0ec986010051662c8e1fbc872c2fd86bc4e
Use FixedSize API.
./src/Workspaces/VisualBasic/Portable/Diagnostics/VisualBasicDiagnosticPropertiesService.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Host.Mef Namespace Microsoft.CodeAnalysis.VisualBasic.Diagnostics <ExportLanguageService(GetType(IDiagnosticPropertiesService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicDiagnosticPropertiesService Inherits AbstractDiagnosticPropertiesService Private Shared ReadOnly s_compilation As Compilation = VisualBasicCompilation.Create("empty") <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overrides Function GetCompilation() As Compilation Return s_compilation End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Host.Mef Namespace Microsoft.CodeAnalysis.VisualBasic.Diagnostics <ExportLanguageService(GetType(IDiagnosticPropertiesService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicDiagnosticPropertiesService Inherits AbstractDiagnosticPropertiesService Private Shared ReadOnly s_compilation As Compilation = VisualBasicCompilation.Create("empty") <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overrides Function GetCompilation() As Compilation Return s_compilation End Function End Class End Namespace
-1
dotnet/roslyn
55,409
Use FixedSize API
tmat
2021-08-04T19:30:40Z
2021-08-04T21:53:46Z
e0112742bff208dd0546de45e36f7b52058a45a3
c90bf0ec986010051662c8e1fbc872c2fd86bc4e
Use FixedSize API.
./src/VisualStudio/Core/Def/Implementation/TableDataSource/Suppression/IVisualStudioDiagnosticListSuppressionStateService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource { /// <summary> /// Service to maintain information about the suppression state of specific set of items in the error list. /// </summary> /// <remarks>TODO: Move to the core platform layer.</remarks> internal interface IVisualStudioDiagnosticListSuppressionStateService { /// <summary> /// Indicates if the top level "Suppress" menu should be visible for the current error list selection. /// </summary> bool CanSuppressSelectedEntries { get; } /// <summary> /// Indicates if sub-menu "(Suppress) In Source" menu should be visible for the current error list selection. /// </summary> bool CanSuppressSelectedEntriesInSource { get; } /// <summary> /// Indicates if sub-menu "(Suppress) In Suppression File" menu should be visible for the current error list selection. /// </summary> bool CanSuppressSelectedEntriesInSuppressionFiles { get; } /// <summary> /// Indicates if the top level "Remove Suppression(s)" menu should be visible for the current error list selection. /// </summary> bool CanRemoveSuppressionsSelectedEntries { 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 namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource { /// <summary> /// Service to maintain information about the suppression state of specific set of items in the error list. /// </summary> /// <remarks>TODO: Move to the core platform layer.</remarks> internal interface IVisualStudioDiagnosticListSuppressionStateService { /// <summary> /// Indicates if the top level "Suppress" menu should be visible for the current error list selection. /// </summary> bool CanSuppressSelectedEntries { get; } /// <summary> /// Indicates if sub-menu "(Suppress) In Source" menu should be visible for the current error list selection. /// </summary> bool CanSuppressSelectedEntriesInSource { get; } /// <summary> /// Indicates if sub-menu "(Suppress) In Suppression File" menu should be visible for the current error list selection. /// </summary> bool CanSuppressSelectedEntriesInSuppressionFiles { get; } /// <summary> /// Indicates if the top level "Remove Suppression(s)" menu should be visible for the current error list selection. /// </summary> bool CanRemoveSuppressionsSelectedEntries { get; } } }
-1
dotnet/roslyn
55,409
Use FixedSize API
tmat
2021-08-04T19:30:40Z
2021-08-04T21:53:46Z
e0112742bff208dd0546de45e36f7b52058a45a3
c90bf0ec986010051662c8e1fbc872c2fd86bc4e
Use FixedSize API.
./src/VisualStudio/Core/Def/Implementation/AbstractOleCommandTarget.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.TextManager.Interop; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation { internal abstract partial class AbstractOleCommandTarget : IOleCommandTarget { /// <summary> /// This is set only during Exec. Currently, this is required to disambiguate the editor calls to /// <see cref="IVsTextViewFilter.GetPairExtents(int, int, TextSpan[])"/> between GotoBrace and GotoBraceExt commands. /// </summary> protected uint CurrentlyExecutingCommand { get; private set; } public AbstractOleCommandTarget( IWpfTextView wpfTextView, IComponentModel componentModel) { Contract.ThrowIfNull(wpfTextView); Contract.ThrowIfNull(componentModel); WpfTextView = wpfTextView; ComponentModel = componentModel; } public IComponentModel ComponentModel { get; } public IVsEditorAdaptersFactoryService EditorAdaptersFactory { get { return ComponentModel.GetService<IVsEditorAdaptersFactoryService>(); } } /// <summary> /// The IWpfTextView that this command filter is attached to. /// </summary> public IWpfTextView WpfTextView { get; } /// <summary> /// The next command target in the chain. This is set by the derived implementation of this /// class. /// </summary> [DisallowNull] protected internal IOleCommandTarget? NextCommandTarget { get; set; } internal AbstractOleCommandTarget AttachToVsTextView() { var vsTextView = EditorAdaptersFactory.GetViewAdapter(WpfTextView); Contract.ThrowIfNull(vsTextView); // Add command filter to IVsTextView. If something goes wrong, throw. var returnValue = vsTextView.AddCommandFilter(this, out var nextCommandTarget); Marshal.ThrowExceptionForHR(returnValue); Contract.ThrowIfNull(nextCommandTarget); NextCommandTarget = nextCommandTarget; return this; } protected virtual ITextBuffer? GetSubjectBufferContainingCaret() => WpfTextView.GetBufferContainingCaret(); protected virtual ITextView ConvertTextView() => WpfTextView; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.TextManager.Interop; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation { internal abstract partial class AbstractOleCommandTarget : IOleCommandTarget { /// <summary> /// This is set only during Exec. Currently, this is required to disambiguate the editor calls to /// <see cref="IVsTextViewFilter.GetPairExtents(int, int, TextSpan[])"/> between GotoBrace and GotoBraceExt commands. /// </summary> protected uint CurrentlyExecutingCommand { get; private set; } public AbstractOleCommandTarget( IWpfTextView wpfTextView, IComponentModel componentModel) { Contract.ThrowIfNull(wpfTextView); Contract.ThrowIfNull(componentModel); WpfTextView = wpfTextView; ComponentModel = componentModel; } public IComponentModel ComponentModel { get; } public IVsEditorAdaptersFactoryService EditorAdaptersFactory { get { return ComponentModel.GetService<IVsEditorAdaptersFactoryService>(); } } /// <summary> /// The IWpfTextView that this command filter is attached to. /// </summary> public IWpfTextView WpfTextView { get; } /// <summary> /// The next command target in the chain. This is set by the derived implementation of this /// class. /// </summary> [DisallowNull] protected internal IOleCommandTarget? NextCommandTarget { get; set; } internal AbstractOleCommandTarget AttachToVsTextView() { var vsTextView = EditorAdaptersFactory.GetViewAdapter(WpfTextView); Contract.ThrowIfNull(vsTextView); // Add command filter to IVsTextView. If something goes wrong, throw. var returnValue = vsTextView.AddCommandFilter(this, out var nextCommandTarget); Marshal.ThrowExceptionForHR(returnValue); Contract.ThrowIfNull(nextCommandTarget); NextCommandTarget = nextCommandTarget; return this; } protected virtual ITextBuffer? GetSubjectBufferContainingCaret() => WpfTextView.GetBufferContainingCaret(); protected virtual ITextView ConvertTextView() => WpfTextView; } }
-1
dotnet/roslyn
55,409
Use FixedSize API
tmat
2021-08-04T19:30:40Z
2021-08-04T21:53:46Z
e0112742bff208dd0546de45e36f7b52058a45a3
c90bf0ec986010051662c8e1fbc872c2fd86bc4e
Use FixedSize API.
./src/Analyzers/VisualBasic/CodeFixes/UseInferredMemberName/VisualBasicUseInferredMemberNameCodeFixProvider.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.UseInferredMemberName Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.UseInferredMemberName <ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.UseInferredMemberName), [Shared]> Friend Class VisualBasicUseInferredMemberNameCodeFixProvider Inherits AbstractUseInferredMemberNameCodeFixProvider <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub Protected Overrides Sub LanguageSpecificRemoveSuggestedNode(editor As SyntaxEditor, node As SyntaxNode) Select Case node.Kind Case SyntaxKind.NameColonEquals editor.RemoveNode(node, SyntaxRemoveOptions.KeepExteriorTrivia Or SyntaxRemoveOptions.AddElasticMarker) Case SyntaxKind.NamedFieldInitializer Dim namedFieldInitializer = DirectCast(node, NamedFieldInitializerSyntax) Dim inferredFieldInitializer = SyntaxFactory.InferredFieldInitializer(namedFieldInitializer.Expression). WithTriviaFrom(namedFieldInitializer) editor.ReplaceNode(namedFieldInitializer, inferredFieldInitializer) End Select End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.UseInferredMemberName Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.UseInferredMemberName <ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.UseInferredMemberName), [Shared]> Friend Class VisualBasicUseInferredMemberNameCodeFixProvider Inherits AbstractUseInferredMemberNameCodeFixProvider <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub Protected Overrides Sub LanguageSpecificRemoveSuggestedNode(editor As SyntaxEditor, node As SyntaxNode) Select Case node.Kind Case SyntaxKind.NameColonEquals editor.RemoveNode(node, SyntaxRemoveOptions.KeepExteriorTrivia Or SyntaxRemoveOptions.AddElasticMarker) Case SyntaxKind.NamedFieldInitializer Dim namedFieldInitializer = DirectCast(node, NamedFieldInitializerSyntax) Dim inferredFieldInitializer = SyntaxFactory.InferredFieldInitializer(namedFieldInitializer.Expression). WithTriviaFrom(namedFieldInitializer) editor.ReplaceNode(namedFieldInitializer, inferredFieldInitializer) End Select End Sub End Class End Namespace
-1
dotnet/roslyn
55,409
Use FixedSize API
tmat
2021-08-04T19:30:40Z
2021-08-04T21:53:46Z
e0112742bff208dd0546de45e36f7b52058a45a3
c90bf0ec986010051662c8e1fbc872c2fd86bc4e
Use FixedSize API.
./src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/ReferencedModulesTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Reflection.PortableExecutable; using Microsoft.Cci; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.DiaSymReader; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.PdbUtilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class ReferencedModulesTests : ExpressionCompilerTestBase { /// <summary> /// MakeAssemblyReferences should drop unreferenced assemblies. /// </summary> [Fact] public void UnreferencedAssemblies() { var (identityMscorlib, moduleMscorlib) = (MscorlibRef.GetAssemblyIdentity(), MscorlibRef.ToModuleInstance()); var (identityIntrinsic, moduleIntrinsic) = (ExpressionCompilerTestHelpers.IntrinsicAssemblyReference.GetAssemblyIdentity(), ExpressionCompilerTestHelpers.IntrinsicAssemblyReference.ToModuleInstance()); var (identityA1, moduleA1, refA1) = Compile("A1", "public class A1 { static void M() { } }"); var (identityA2, moduleA2, refA2) = Compile("A2", "public class A2 { static void M() { } }"); var (identityB1, moduleB1, refB1) = Compile("B1", "public class B1 : A1 { static void M() { } }", refA1); var (identityB2, moduleB2, refB2) = Compile("B2", "public class B2 : A1 { static void M() { } }", refA1); var (identityC, moduleC, refC) = Compile("C", "public class C1 : B2 { static void M() { } } public class C2 : A2 { }", refA1, refA2, refB2); using (var runtime = CreateRuntimeInstance(new[] { moduleMscorlib, moduleA1, moduleA2, moduleB1, moduleB2, moduleC })) { var stateB2 = GetContextState(runtime, "B2.M"); // B2.M with missing A1. var context = CreateMethodContext( new AppDomain(), ImmutableArray.Create(moduleMscorlib, moduleA2, moduleB1, moduleB2, moduleC).SelectAsArray(m => m.MetadataBlock), stateB2); ResultProperties resultProperties; string error; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; context.CompileExpression("new B2()", DkmEvaluationFlags.TreatAsExpression, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Equal("error CS0012: The type 'A1' is defined in an assembly that is not referenced. You must add a reference to assembly 'A1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.", error); AssertEx.Equal(new[] { identityA1 }, missingAssemblyIdentities); VerifyResolutionRequests(context, (identityA1, null, 1)); // B2.M with all assemblies. context = CreateMethodContext( new AppDomain(), ImmutableArray.Create(moduleMscorlib, moduleA1, moduleA2, moduleB1, moduleB2, moduleC).SelectAsArray(m => m.MetadataBlock), stateB2); var testData = new CompilationTestData(); context.CompileExpression("new B2()", out error, testData); var methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""B2..ctor()"" IL_0005: ret }"); VerifyResolutionRequests(context, (identityA1, identityA1, 1)); // B2.M with all assemblies in reverse order. context = CreateMethodContext( new AppDomain(), ImmutableArray.Create(moduleC, moduleB2, moduleB1, moduleA2, moduleA1, moduleMscorlib, moduleIntrinsic).SelectAsArray(m => m.MetadataBlock), stateB2); testData = new CompilationTestData(); context.CompileExpression("new B2()", out error, testData); methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""B2..ctor()"" IL_0005: ret }"); VerifyResolutionRequests(context, (identityA1, identityA1, 1)); // A1.M with all assemblies. var stateA1 = GetContextState(runtime, "A1.M"); context = CreateMethodContext( new AppDomain(), ImmutableArray.Create(moduleMscorlib, moduleA1, moduleA2, moduleB1, moduleB2, moduleC).SelectAsArray(m => m.MetadataBlock), stateA1); testData = new CompilationTestData(); context.CompileExpression("new A1()", out error, testData); methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""A1..ctor()"" IL_0005: ret }"); VerifyResolutionRequests(context); // B1.M with all assemblies. var stateB1 = GetContextState(runtime, "B1.M"); context = CreateMethodContext( new AppDomain(), ImmutableArray.Create(moduleMscorlib, moduleA1, moduleA2, moduleB1, moduleB2, moduleC).SelectAsArray(m => m.MetadataBlock), stateB1); testData = new CompilationTestData(); context.CompileExpression("new B1()", out error, testData); methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""B1..ctor()"" IL_0005: ret }"); VerifyResolutionRequests(context, (identityA1, identityA1, 1)); // C1.M with all assemblies. var stateC = GetContextState(runtime, "C1.M"); context = CreateMethodContext( new AppDomain(), ImmutableArray.Create(moduleMscorlib, moduleA1, moduleA2, moduleB1, moduleB2, moduleC).SelectAsArray(m => m.MetadataBlock), stateC); testData = new CompilationTestData(); context.CompileExpression("new C1()", out error, testData); methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""C1..ctor()"" IL_0005: ret }"); VerifyResolutionRequests(context, (identityB2, identityB2, 1), (identityA1, identityA1, 1), (identityA2, identityA2, 1)); // Other EvaluationContext.CreateMethodContext overload. // A1.M with all assemblies. var allBlocks = ImmutableArray.Create(moduleMscorlib, moduleA1, moduleA2, moduleB1, moduleB2, moduleC).SelectAsArray(m => m.MetadataBlock); context = EvaluationContext.CreateMethodContext( allBlocks, stateA1.SymReader, stateA1.ModuleVersionId, stateA1.MethodToken, methodVersion: 1, stateA1.ILOffset, stateA1.LocalSignatureToken); testData = new CompilationTestData(); context.CompileExpression("new B1()", out error, testData); methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""B1..ctor()"" IL_0005: ret }"); // Other EvaluationContext.CreateMethodContext overload. // A1.M with all assemblies, offset outside of IL. context = EvaluationContext.CreateMethodContext( allBlocks, stateA1.SymReader, stateA1.ModuleVersionId, stateA1.MethodToken, methodVersion: 1, uint.MaxValue, stateA1.LocalSignatureToken); testData = new CompilationTestData(); context.CompileExpression("new C1()", out error, testData); methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""C1..ctor()"" IL_0005: ret }"); } } [Fact] public void DifferentAssemblyVersions() { var publicKeyA = ImmutableArray.CreateRange(new byte[] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00, 0x06, 0x02, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x52, 0x53, 0x41, 0x31, 0x00, 0x04, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0xED, 0xD3, 0x22, 0xCB, 0x6B, 0xF8, 0xD4, 0xA2, 0xFC, 0xCC, 0x87, 0x37, 0x04, 0x06, 0x04, 0xCE, 0xE7, 0xB2, 0xA6, 0xF8, 0x4A, 0xEE, 0xF3, 0x19, 0xDF, 0x5B, 0x95, 0xE3, 0x7A, 0x6A, 0x28, 0x24, 0xA4, 0x0A, 0x83, 0x83, 0xBD, 0xBA, 0xF2, 0xF2, 0x52, 0x20, 0xE9, 0xAA, 0x3B, 0xD1, 0xDD, 0xE4, 0x9A, 0x9A, 0x9C, 0xC0, 0x30, 0x8F, 0x01, 0x40, 0x06, 0xE0, 0x2B, 0x95, 0x62, 0x89, 0x2A, 0x34, 0x75, 0x22, 0x68, 0x64, 0x6E, 0x7C, 0x2E, 0x83, 0x50, 0x5A, 0xCE, 0x7B, 0x0B, 0xE8, 0xF8, 0x71, 0xE6, 0xF7, 0x73, 0x8E, 0xEB, 0x84, 0xD2, 0x73, 0x5D, 0x9D, 0xBE, 0x5E, 0xF5, 0x90, 0xF9, 0xAB, 0x0A, 0x10, 0x7E, 0x23, 0x48, 0xF4, 0xAD, 0x70, 0x2E, 0xF7, 0xD4, 0x51, 0xD5, 0x8B, 0x3A, 0xF7, 0xCA, 0x90, 0x4C, 0xDC, 0x80, 0x19, 0x26, 0x65, 0xC9, 0x37, 0xBD, 0x52, 0x81, 0xF1, 0x8B, 0xCD }); var options = TestOptions.DebugDll.WithDelaySign(true); var (identityMscorlib, moduleMscorlib) = (MscorlibRef.GetAssemblyIdentity(), MscorlibRef.ToModuleInstance()); var (identityA1, moduleA1, refA1) = Compile(new AssemblyIdentity("A", new Version(1, 1, 1, 1), publicKeyOrToken: publicKeyA, hasPublicKey: true), "public class A { }", options, MscorlibRef); var (identityA2, moduleA2, refA2) = Compile(new AssemblyIdentity("A", new Version(2, 2, 2, 2), publicKeyOrToken: publicKeyA, hasPublicKey: true), "public class A { }", options, MscorlibRef); var (identityA3, moduleA3, refA3) = Compile(new AssemblyIdentity("a", new Version(3, 3, 3, 3), publicKeyOrToken: publicKeyA, hasPublicKey: true), "public class A { }", options, MscorlibRef); var (identityB1, moduleB1, refB1) = Compile(new AssemblyIdentity("B", new Version(1, 1, 1, 1)), "public class B : A { static void M() { } }", TestOptions.DebugDll, refA2, MscorlibRef); using (var runtime = CreateRuntimeInstance(new[] { moduleMscorlib, moduleA1, moduleA2, moduleA3, moduleB1 })) { var stateB = GetContextState(runtime, "B.M"); // Expected version of A. var context = CreateMethodContext( new AppDomain(), ImmutableArray.Create(moduleMscorlib, moduleA2, moduleB1).SelectAsArray(m => m.MetadataBlock), stateB); string error; var testData = new CompilationTestData(); context.CompileExpression("new B()", out error, testData); var methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""B..ctor()"" IL_0005: ret }"); VerifyResolutionRequests(context, (identityA2, identityA2, 1)); // Higher version of A. context = CreateMethodContext( new AppDomain(), ImmutableArray.Create(moduleMscorlib, moduleA3, moduleB1).SelectAsArray(m => m.MetadataBlock), stateB); testData = new CompilationTestData(); context.CompileExpression("new B()", out error, testData); methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""B..ctor()"" IL_0005: ret }"); VerifyResolutionRequests(context, (identityA2, identityA3, 1)); // Lower version of A. context = CreateMethodContext( new AppDomain(), ImmutableArray.Create(moduleMscorlib, moduleA1, moduleB1).SelectAsArray(m => m.MetadataBlock), stateB); testData = new CompilationTestData(); context.CompileExpression("new B()", out error, testData); Assert.Equal("error CS1705: Assembly 'B' with identity 'B, Version=1.1.1.1, Culture=neutral, PublicKeyToken=null' uses 'A, Version=2.2.2.2, Culture=neutral, PublicKeyToken=1f8a32457d187bf3' which has a higher version than referenced assembly 'A' with identity 'A, Version=1.1.1.1, Culture=neutral, PublicKeyToken=1f8a32457d187bf3'", error); VerifyResolutionRequests(context, (identityA2, identityA1, 1)); // Multiple versions of A. context = CreateMethodContext( new AppDomain(), ImmutableArray.Create(moduleMscorlib, moduleA1, moduleA3, moduleA2, moduleB1).SelectAsArray(m => m.MetadataBlock), stateB); testData = new CompilationTestData(); context.CompileExpression("new B()", out error, testData); methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""B..ctor()"" IL_0005: ret }"); VerifyResolutionRequests(context, (identityA2, identityA2, 1)); // Duplicate versions of A. context = CreateMethodContext( new AppDomain(), ImmutableArray.Create(moduleMscorlib, moduleA3, moduleA1, moduleA3, moduleA1, moduleB1).SelectAsArray(m => m.MetadataBlock), stateB); testData = new CompilationTestData(); context.CompileExpression("new B()", out error, testData); methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""B..ctor()"" IL_0005: ret }"); VerifyResolutionRequests(context, (identityA2, identityA3, 1)); } } // Not handling duplicate corlib when using referenced assemblies // only (bug #...). [Fact(Skip = "TODO")] public void DuplicateNamedCorLib() { var publicKeyOther = ImmutableArray.CreateRange(new byte[] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00, 0x06, 0x02, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x52, 0x53, 0x41, 0x31, 0x00, 0x04, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0xED, 0xD3, 0x22, 0xCB, 0x6B, 0xF8, 0xD4, 0xA2, 0xFC, 0xCC, 0x87, 0x37, 0x04, 0x06, 0x04, 0xCE, 0xE7, 0xB2, 0xA6, 0xF8, 0x4A, 0xEE, 0xF3, 0x19, 0xDF, 0x5B, 0x95, 0xE3, 0x7A, 0x6A, 0x28, 0x24, 0xA4, 0x0A, 0x83, 0x83, 0xBD, 0xBA, 0xF2, 0xF2, 0x52, 0x20, 0xE9, 0xAA, 0x3B, 0xD1, 0xDD, 0xE4, 0x9A, 0x9A, 0x9C, 0xC0, 0x30, 0x8F, 0x01, 0x40, 0x06, 0xE0, 0x2B, 0x95, 0x62, 0x89, 0x2A, 0x34, 0x75, 0x22, 0x68, 0x64, 0x6E, 0x7C, 0x2E, 0x83, 0x50, 0x5A, 0xCE, 0x7B, 0x0B, 0xE8, 0xF8, 0x71, 0xE6, 0xF7, 0x73, 0x8E, 0xEB, 0x84, 0xD2, 0x73, 0x5D, 0x9D, 0xBE, 0x5E, 0xF5, 0x90, 0xF9, 0xAB, 0x0A, 0x10, 0x7E, 0x23, 0x48, 0xF4, 0xAD, 0x70, 0x2E, 0xF7, 0xD4, 0x51, 0xD5, 0x8B, 0x3A, 0xF7, 0xCA, 0x90, 0x4C, 0xDC, 0x80, 0x19, 0x26, 0x65, 0xC9, 0x37, 0xBD, 0x52, 0x81, 0xF1, 0x8B, 0xCD }); var options = TestOptions.DebugDll.WithDelaySign(true); var (identityMscorlib, moduleMscorlib) = (MscorlibRef.GetAssemblyIdentity(), MscorlibRef.ToModuleInstance()); var (identityOther, moduleOther, refOther) = Compile(new AssemblyIdentity(identityMscorlib.Name, new Version(1, 1, 1, 1), publicKeyOrToken: publicKeyOther, hasPublicKey: true), "class Other { }", options, MscorlibRef); var (identityA, moduleA, refA) = Compile(new AssemblyIdentity("A", new Version(1, 1, 1, 1)), "public class A { }", TestOptions.DebugDll, refOther, MscorlibRef); var (identityB, moduleB, refB) = Compile(new AssemblyIdentity("B", new Version(1, 1, 1, 1)), "public class B : A { static void M() { } }", TestOptions.DebugDll, refA, refOther, MscorlibRef); using (var runtime = CreateRuntimeInstance(new[] { moduleMscorlib, moduleA, moduleB })) { var stateB = GetContextState(runtime, "B.M"); var (moduleVersionId, symReader, methodToken, localSignatureToken, ilOffset) = GetContextState(runtime, "B.M"); var context = CreateMethodContext( new AppDomain(), ImmutableArray.Create(moduleMscorlib, moduleOther, moduleA, moduleB).SelectAsArray(m => m.MetadataBlock), stateB); string error; var testData = new CompilationTestData(); context.CompileExpression("new B()", out error, testData); var methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""B..ctor()"" IL_0005: ret }"); VerifyResolutionRequests(context, (identityA, identityA, 1)); context = CreateMethodContext( new AppDomain(), ImmutableArray.Create(moduleB, moduleA, moduleOther, moduleMscorlib).SelectAsArray(m => m.MetadataBlock), stateB); testData = new CompilationTestData(); context.CompileExpression("new B()", out error, testData); methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""B..ctor()"" IL_0005: ret }"); VerifyResolutionRequests(context, (identityA, identityA, 1)); } } /// <summary> /// Reuse compilation across evaluations unless current assembly changes. /// </summary> [Fact] public void ReuseCompilation() { var (identityMscorlib, moduleMscorlib) = (MscorlibRef.GetAssemblyIdentity(), MscorlibRef.ToModuleInstance()); var (identityA1, moduleA1, refA1) = Compile("A1", "public class A1 { static void M() { } }"); var (identityA2, moduleA2, refA2) = Compile("A2", "public class A2 { static void M() { } } public class A3 { static void M() { } }"); var (identityB1, moduleB1, refB1) = Compile("B1", "public class B1 : A1 { static void M() { } } public class B2 { static void M() { } }", refA1); using (var runtime = CreateRuntimeInstance(new[] { moduleMscorlib, moduleA1, moduleA2, moduleB1 })) { var blocks = runtime.Modules.SelectAsArray(m => m.MetadataBlock); var stateA1 = GetContextState(runtime, "A1.M"); var stateA2 = GetContextState(runtime, "A2.M"); var stateA3 = GetContextState(runtime, "A3.M"); var stateB1 = GetContextState(runtime, "B1.M"); var stateB2 = GetContextState(runtime, "B2.M"); var mvidA1 = stateA1.ModuleVersionId; var mvidA2 = stateA2.ModuleVersionId; var mvidB1 = stateB1.ModuleVersionId; Assert.Equal(mvidB1, stateB2.ModuleVersionId); EvaluationContext context; MetadataContext<CSharpMetadataContext> previous; // B1 -> B2 -> A1 -> A2 -> A3 // B1.M: var appDomain = new AppDomain(); previous = appDomain.GetMetadataContext(); context = CreateMethodContext(appDomain, blocks, stateB1); VerifyResolutionRequests(context, (identityA1, identityA1, 1)); VerifyAppDomainMetadataContext(appDomain, mvidB1); // B2.M: previous = appDomain.GetMetadataContext(); context = CreateMethodContext(appDomain, blocks, stateB2); Assert.NotSame(context, GetMetadataContext(previous, mvidB1).EvaluationContext); Assert.Same(context.Compilation, GetMetadataContext(previous, mvidB1).Compilation); VerifyResolutionRequests(context, (identityA1, identityA1, 1)); VerifyAppDomainMetadataContext(appDomain, mvidB1); // A1.M: previous = appDomain.GetMetadataContext(); context = CreateMethodContext(appDomain, blocks, stateA1); Assert.NotSame(context, GetMetadataContext(previous, mvidB1).EvaluationContext); Assert.NotSame(context.Compilation, GetMetadataContext(previous, mvidB1).Compilation); VerifyResolutionRequests(context); VerifyAppDomainMetadataContext(appDomain, mvidB1, mvidA1); // A2.M: previous = appDomain.GetMetadataContext(); context = CreateMethodContext(appDomain, blocks, stateA2); Assert.NotSame(context, GetMetadataContext(previous, mvidA1).EvaluationContext); Assert.NotSame(context.Compilation, GetMetadataContext(previous, mvidA1).Compilation); VerifyResolutionRequests(context); VerifyAppDomainMetadataContext(appDomain, mvidB1, mvidA1, mvidA2); // A3.M: previous = appDomain.GetMetadataContext(); context = CreateMethodContext(appDomain, blocks, stateA3); Assert.NotSame(context, GetMetadataContext(previous, mvidA2).EvaluationContext); Assert.Same(context.Compilation, GetMetadataContext(previous, mvidA2).Compilation); VerifyResolutionRequests(context); VerifyAppDomainMetadataContext(appDomain, mvidB1, mvidA1, mvidA2); // A1 -> A2 -> A3 -> B1 -> B2 // A1.M: appDomain = new AppDomain(); context = CreateMethodContext(appDomain, blocks, stateA1); VerifyResolutionRequests(context); VerifyAppDomainMetadataContext(appDomain, mvidA1); // A2.M: previous = appDomain.GetMetadataContext(); context = CreateMethodContext(appDomain, blocks, stateA2); Assert.NotSame(context, GetMetadataContext(previous, mvidA1).EvaluationContext); Assert.NotSame(context.Compilation, GetMetadataContext(previous, mvidA1).Compilation); VerifyResolutionRequests(context); VerifyAppDomainMetadataContext(appDomain, mvidA1, mvidA2); // A3.M: previous = appDomain.GetMetadataContext(); context = CreateMethodContext(appDomain, blocks, stateA3); Assert.NotSame(context, GetMetadataContext(previous, mvidA2).EvaluationContext); Assert.Same(context.Compilation, GetMetadataContext(previous, mvidA2).Compilation); VerifyResolutionRequests(context); VerifyAppDomainMetadataContext(appDomain, mvidA1, mvidA2); // B1.M: previous = appDomain.GetMetadataContext(); context = CreateMethodContext(appDomain, blocks, stateB1); Assert.NotSame(context, GetMetadataContext(previous, mvidA2).EvaluationContext); Assert.NotSame(context.Compilation, GetMetadataContext(previous, mvidA2).Compilation); VerifyResolutionRequests(context, (identityA1, identityA1, 1)); VerifyAppDomainMetadataContext(appDomain, mvidA1, mvidA2, mvidB1); // B2.M: previous = appDomain.GetMetadataContext(); context = CreateMethodContext(appDomain, blocks, stateB2); Assert.NotSame(context, GetMetadataContext(previous, mvidB1).EvaluationContext); Assert.Same(context.Compilation, GetMetadataContext(previous, mvidB1).Compilation); VerifyResolutionRequests(context, (identityA1, identityA1, 1)); VerifyAppDomainMetadataContext(appDomain, mvidA1, mvidA2, mvidB1); } } private static void VerifyAppDomainMetadataContext(AppDomain appDomain, params Guid[] moduleVersionIds) { ExpressionCompilerTestHelpers.VerifyAppDomainMetadataContext(appDomain.GetMetadataContext(), moduleVersionIds); } [WorkItem(26159, "https://github.com/dotnet/roslyn/issues/26159")] [Fact] public void TypeOutsideAssemblyReferences() { var sourceA = @"public class A { void M() { } }"; var sourceB = @"#pragma warning disable 169 class B : A { object F; }"; var (identityMscorlib, moduleMscorlib) = (MscorlibRef.GetAssemblyIdentity(), MscorlibRef.ToModuleInstance()); var (identityA, moduleA, refA) = Compile("A", sourceA); var (identityB, moduleB, refB) = Compile("B", sourceB, refA); using (var runtime = CreateRuntimeInstance(new[] { moduleMscorlib, moduleA, moduleB })) { var blocks = runtime.Modules.SelectAsArray(m => m.MetadataBlock); var stateA = GetContextState(runtime, "A.M"); const string expr = "((B)this).F"; // A.M, all assemblies var context = CreateMethodContext(new AppDomain(), blocks, stateA, MakeAssemblyReferencesKind.AllAssemblies); string error; var testData = new CompilationTestData(); context.CompileExpression(expr, out error, testData); var methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: castclass ""B"" IL_0006: ldfld ""object B.F"" IL_000b: ret }"); // A.M, all referenced assemblies context = CreateMethodContext(new AppDomain(), blocks, stateA, MakeAssemblyReferencesKind.AllReferences); testData = new CompilationTestData(); context.CompileExpression(expr, out error, testData); Assert.Equal("error CS0246: The type or namespace name 'B' could not be found (are you missing a using directive or an assembly reference?)", error); } } [WorkItem(1141029, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1141029")] [Fact] public void AssemblyDuplicateReferences() { var sourceA = @"public class A { }"; var sourceB = @"public class B { public A F = new A(); }"; var sourceC = @"class C { private B F = new B(); static void M() { } }"; // Assembly A, multiple versions, strong name. var assemblyNameA = ExpressionCompilerUtilities.GenerateUniqueName(); var publicKeyA = ImmutableArray.CreateRange(new byte[] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00, 0x06, 0x02, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x52, 0x53, 0x41, 0x31, 0x00, 0x04, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0xED, 0xD3, 0x22, 0xCB, 0x6B, 0xF8, 0xD4, 0xA2, 0xFC, 0xCC, 0x87, 0x37, 0x04, 0x06, 0x04, 0xCE, 0xE7, 0xB2, 0xA6, 0xF8, 0x4A, 0xEE, 0xF3, 0x19, 0xDF, 0x5B, 0x95, 0xE3, 0x7A, 0x6A, 0x28, 0x24, 0xA4, 0x0A, 0x83, 0x83, 0xBD, 0xBA, 0xF2, 0xF2, 0x52, 0x20, 0xE9, 0xAA, 0x3B, 0xD1, 0xDD, 0xE4, 0x9A, 0x9A, 0x9C, 0xC0, 0x30, 0x8F, 0x01, 0x40, 0x06, 0xE0, 0x2B, 0x95, 0x62, 0x89, 0x2A, 0x34, 0x75, 0x22, 0x68, 0x64, 0x6E, 0x7C, 0x2E, 0x83, 0x50, 0x5A, 0xCE, 0x7B, 0x0B, 0xE8, 0xF8, 0x71, 0xE6, 0xF7, 0x73, 0x8E, 0xEB, 0x84, 0xD2, 0x73, 0x5D, 0x9D, 0xBE, 0x5E, 0xF5, 0x90, 0xF9, 0xAB, 0x0A, 0x10, 0x7E, 0x23, 0x48, 0xF4, 0xAD, 0x70, 0x2E, 0xF7, 0xD4, 0x51, 0xD5, 0x8B, 0x3A, 0xF7, 0xCA, 0x90, 0x4C, 0xDC, 0x80, 0x19, 0x26, 0x65, 0xC9, 0x37, 0xBD, 0x52, 0x81, 0xF1, 0x8B, 0xCD }); var compilationAS1 = CreateCompilation( new AssemblyIdentity(assemblyNameA, new Version(1, 1, 1, 1), cultureName: "", publicKeyOrToken: publicKeyA, hasPublicKey: true), new[] { sourceA }, references: new[] { MscorlibRef }, options: TestOptions.DebugDll.WithDelaySign(true)); var referenceAS1 = compilationAS1.EmitToImageReference(); var identityAS1 = referenceAS1.GetAssemblyIdentity(); var compilationAS2 = CreateCompilation( new AssemblyIdentity(assemblyNameA, new Version(2, 1, 1, 1), cultureName: "", publicKeyOrToken: publicKeyA, hasPublicKey: true), new[] { sourceA }, references: new[] { MscorlibRef }, options: TestOptions.DebugDll.WithDelaySign(true)); var referenceAS2 = compilationAS2.EmitToImageReference(); var identityAS2 = referenceAS2.GetAssemblyIdentity(); // Assembly B, multiple versions, not strong name. var assemblyNameB = ExpressionCompilerUtilities.GenerateUniqueName(); var compilationBN1 = CreateCompilation( new AssemblyIdentity(assemblyNameB, new Version(1, 1, 1, 1)), new[] { sourceB }, references: new[] { MscorlibRef, referenceAS1 }, options: TestOptions.DebugDll); var referenceBN1 = compilationBN1.EmitToImageReference(); var identityBN1 = referenceBN1.GetAssemblyIdentity(); var compilationBN2 = CreateCompilation( new AssemblyIdentity(assemblyNameB, new Version(2, 2, 2, 1)), new[] { sourceB }, references: new[] { MscorlibRef, referenceAS1 }, options: TestOptions.DebugDll); var referenceBN2 = compilationBN2.EmitToImageReference(); var identityBN2 = referenceBN2.GetAssemblyIdentity(); // Assembly B, multiple versions, strong name. var publicKeyB = ImmutableArray.CreateRange(new byte[] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00, 0x06, 0x02, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x53, 0x52, 0x41, 0x31, 0x00, 0x04, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0xED, 0xD3, 0x22, 0xCB, 0x6B, 0xF8, 0xD4, 0xA2, 0xFC, 0xCC, 0x87, 0x37, 0x04, 0x06, 0x04, 0xCE, 0xE7, 0xB2, 0xA6, 0xF8, 0x4A, 0xEE, 0xF3, 0x19, 0xDF, 0x5B, 0x95, 0xE3, 0x7A, 0x6A, 0x28, 0x24, 0xA4, 0x0A, 0x83, 0x83, 0xBD, 0xBA, 0xF2, 0xF2, 0x52, 0x20, 0xE9, 0xAA, 0x3B, 0xD1, 0xDD, 0xE4, 0x9A, 0x9A, 0x9C, 0xC0, 0x30, 0x8F, 0x01, 0x40, 0x06, 0xE0, 0x2B, 0x95, 0x62, 0x89, 0x2A, 0x34, 0x75, 0x22, 0x68, 0x64, 0x6E, 0x7C, 0x2E, 0x83, 0x50, 0x5A, 0xCE, 0x7B, 0x0B, 0xE8, 0xF8, 0x71, 0xE6, 0xF7, 0x73, 0x8E, 0xEB, 0x84, 0xD2, 0x73, 0x5D, 0x9D, 0xBE, 0x5E, 0xF5, 0x90, 0xF9, 0xAB, 0x0A, 0x10, 0x7E, 0x23, 0x48, 0xF4, 0xAD, 0x70, 0x2E, 0xF7, 0xD4, 0x51, 0xD5, 0x8B, 0x3A, 0xF7, 0xCA, 0x90, 0x4C, 0xDC, 0x80, 0x19, 0x26, 0x65, 0xC9, 0x37, 0xBD, 0x52, 0x81, 0xF1, 0x8B, 0xCD }); var compilationBS1 = CreateCompilation( new AssemblyIdentity(assemblyNameB, new Version(1, 1, 1, 1), cultureName: "", publicKeyOrToken: publicKeyB, hasPublicKey: true), new[] { sourceB }, references: new[] { MscorlibRef, referenceAS1 }, options: TestOptions.DebugDll.WithDelaySign(true)); var referenceBS1 = compilationBS1.EmitToImageReference(); var identityBS1 = referenceBS1.GetAssemblyIdentity(); var compilationBS2 = CreateCompilation( new AssemblyIdentity(assemblyNameB, new Version(2, 2, 2, 1), cultureName: "", publicKeyOrToken: publicKeyB, hasPublicKey: true), new[] { sourceB }, references: new[] { MscorlibRef, referenceAS2 }, options: TestOptions.DebugDll.WithDelaySign(true)); var referenceBS2 = compilationBS2.EmitToImageReference(); var identityBS2 = referenceBS2.GetAssemblyIdentity(); var mscorlibIdentity = MscorlibRef.GetAssemblyIdentity(); var mscorlib20Identity = MscorlibRef_v20.GetAssemblyIdentity(); var systemRefIdentity = SystemRef.GetAssemblyIdentity(); var systemRef20Identity = SystemRef_v20.GetAssemblyIdentity(); // No duplicates. VerifyAssemblyReferences( referenceBN1, ImmutableArray.Create(MscorlibRef, referenceAS1, referenceBN1), ImmutableArray.Create(mscorlibIdentity, identityAS1, identityBN1)); // No duplicates, extra references. VerifyAssemblyReferences( referenceAS1, ImmutableArray.Create(MscorlibRef, referenceBN1, referenceAS1, referenceBS2), ImmutableArray.Create(mscorlibIdentity, identityAS1)); // Strong-named, non-strong-named, and framework duplicates, same version (no aliases). VerifyAssemblyReferences( referenceBN2, ImmutableArray.Create(MscorlibRef, referenceAS1, MscorlibRef, referenceBN2, referenceBN2, referenceAS1, referenceAS1), ImmutableArray.Create(mscorlibIdentity, identityAS1, identityBN2)); // Strong-named, non-strong-named, and framework duplicates, different versions. VerifyAssemblyReferences( referenceBN1, ImmutableArray.Create(MscorlibRef, referenceAS1, MscorlibRef_v20, referenceAS2, referenceBN2, referenceBN1, referenceAS2, referenceAS1, referenceBN1), ImmutableArray.Create(mscorlibIdentity, identityAS2, identityBN2)); VerifyAssemblyReferences( referenceBN2, ImmutableArray.Create(MscorlibRef, referenceAS1, MscorlibRef_v20, referenceAS2, referenceBN2, referenceBN1, referenceAS2, referenceAS1, referenceBN1), ImmutableArray.Create(mscorlibIdentity, identityAS2, identityBN2)); // Strong-named, different versions. VerifyAssemblyReferences( referenceBS1, ImmutableArray.Create(MscorlibRef, referenceAS1, referenceAS2, referenceBS2, referenceBS1, referenceAS2, referenceAS1, referenceBS1), ImmutableArray.Create(mscorlibIdentity, identityAS2, identityBS2)); VerifyAssemblyReferences( referenceBS2, ImmutableArray.Create(MscorlibRef, referenceAS1, referenceAS2, referenceBS2, referenceBS1, referenceAS2, referenceAS1, referenceBS1), ImmutableArray.Create(mscorlibIdentity, identityAS2, identityBS2)); // Assembly C, multiple versions, not strong name. var compilationCN1 = CreateCompilation( new AssemblyIdentity("C", new Version(1, 1, 1, 1)), new[] { sourceC }, references: new[] { MscorlibRef, referenceBS1 }, options: TestOptions.DebugDll); // Duplicate assemblies, target module referencing BS1. WithRuntimeInstance(compilationCN1, new[] { MscorlibRef, referenceAS1, referenceAS2, referenceBS2, referenceBS1, referenceBS2 }, runtime => { ImmutableArray<MetadataBlock> typeBlocks; ImmutableArray<MetadataBlock> methodBlocks; Guid moduleVersionId; ISymUnmanagedReader symReader; int typeToken; int methodToken; int localSignatureToken; GetContextState(runtime, "C", out typeBlocks, out moduleVersionId, out symReader, out typeToken, out localSignatureToken); GetContextState(runtime, "C.M", out methodBlocks, out moduleVersionId, out symReader, out methodToken, out localSignatureToken); uint ilOffset = ExpressionCompilerTestHelpers.GetOffset(methodToken, symReader); // Compile expression with type context with all modules. var appDomain = new AppDomain(); var context = CreateTypeContext( appDomain, typeBlocks, moduleVersionId, typeToken, MakeAssemblyReferencesKind.AllAssemblies); Assert.Equal(identityAS2, context.Compilation.GlobalNamespace.GetMembers("A").OfType<NamedTypeSymbol>().Single().ContainingAssembly.Identity); Assert.Equal(identityBS2, context.Compilation.GlobalNamespace.GetMembers("B").OfType<NamedTypeSymbol>().Single().ContainingAssembly.Identity); string error; // A could be ambiguous, but the ambiguity is resolved in favor of the newer assembly. var testData = new CompilationTestData(); context.CompileExpression("new A()", out error, testData); Assert.Null(error); // B could be ambiguous, but the ambiguity is resolved in favor of the newer assembly. testData = new CompilationTestData(); context.CompileExpression("new B()", out error, testData); Assert.Null(error); appDomain.SetMetadataContext( SetMetadataContext( new MetadataContext<CSharpMetadataContext>(typeBlocks, ImmutableDictionary<MetadataContextId, CSharpMetadataContext>.Empty), default(Guid), new CSharpMetadataContext(context.Compilation))); // Compile expression with type context with referenced modules only. context = CreateTypeContext( appDomain, typeBlocks, moduleVersionId, typeToken, MakeAssemblyReferencesKind.DirectReferencesOnly); // A is unrecognized since there were no direct references to AS1 or AS2. testData = new CompilationTestData(); context.CompileExpression("new A()", out error, testData); Assert.Equal("error CS0246: The type or namespace name 'A' could not be found (are you missing a using directive or an assembly reference?)", error); testData = new CompilationTestData(); // B should be resolved to BS2. context.CompileExpression("new B()", out error, testData); var methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""B..ctor()"" IL_0005: ret }"); Assert.Equal(((MethodSymbol)methodData.Method).ReturnType.ContainingAssembly.ToDisplayString(), identityBS2.GetDisplayName()); // B.F should result in missing assembly AS2 since there were no direct references to AS2. ResultProperties resultProperties; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; testData = new CompilationTestData(); context.CompileExpression( "(new B()).F", DkmEvaluationFlags.None, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); AssertEx.Equal(missingAssemblyIdentities, ImmutableArray.Create(identityAS2)); // Compile expression with method context with all modules. var previous = appDomain.GetMetadataContext(); context = CreateMethodContext( appDomain, methodBlocks, symReader, moduleVersionId, methodToken: methodToken, methodVersion: 1, ilOffset: ilOffset, localSignatureToken: localSignatureToken, MakeAssemblyReferencesKind.AllAssemblies); Assert.NotSame(GetMetadataContext(previous).EvaluationContext, context); Assert.Same(GetMetadataContext(previous).Compilation, context.Compilation); // re-use type context compilation testData = new CompilationTestData(); // A could be ambiguous, but the ambiguity is resolved in favor of the newer assembly. testData = new CompilationTestData(); context.CompileExpression("new A()", out error, testData); Assert.Null(error); // B could be ambiguous, but the ambiguity is resolved in favor of the newer assembly. testData = new CompilationTestData(); context.CompileExpression("new B()", out error, testData); Assert.Null(error); // Compile expression with method context with referenced modules only. context = CreateMethodContext( appDomain, methodBlocks, symReader, moduleVersionId, methodToken: methodToken, methodVersion: 1, ilOffset: ilOffset, localSignatureToken: localSignatureToken, MakeAssemblyReferencesKind.DirectReferencesOnly); // A is unrecognized since there were no direct references to AS1 or AS2. testData = new CompilationTestData(); context.CompileExpression("new A()", out error, testData); Assert.Equal("error CS0246: The type or namespace name 'A' could not be found (are you missing a using directive or an assembly reference?)", error); testData = new CompilationTestData(); // B should be resolved to BS2. context.CompileExpression("new B()", out error, testData); methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""B..ctor()"" IL_0005: ret }"); Assert.Equal(((MethodSymbol)methodData.Method).ReturnType.ContainingAssembly.ToDisplayString(), identityBS2.GetDisplayName()); // B.F should result in missing assembly AS2 since there were no direct references to AS2. testData = new CompilationTestData(); context.CompileExpression( "(new B()).F", DkmEvaluationFlags.None, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); AssertEx.Equal(missingAssemblyIdentities, ImmutableArray.Create(identityAS2)); }); } private static (AssemblyIdentity Identity, ModuleInstance Module, MetadataReference Reference) Compile(string assemblyName, string source, params MetadataReference[] references) { var compilation = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, references: references, assemblyName: assemblyName); compilation.VerifyDiagnostics(); var module = compilation.ToModuleInstance(); return (compilation.Assembly.Identity, module, module.GetReference()); } private static (AssemblyIdentity Identity, ModuleInstance Module, MetadataReference Reference) Compile(AssemblyIdentity identity, string source, CSharpCompilationOptions options, params MetadataReference[] references) { var compilation = CreateCompilation(identity, new[] { source }, references: references, options: options); compilation.VerifyDiagnostics(); var module = compilation.ToModuleInstance(); return (compilation.Assembly.Identity, module, module.GetReference()); } private static void VerifyAssemblyReferences( MetadataReference target, ImmutableArray<MetadataReference> references, ImmutableArray<AssemblyIdentity> expectedIdentities) { Assert.True(references.Contains(target)); var modules = references.SelectAsArray(r => r.ToModuleInstance()); using (var runtime = new RuntimeInstance(modules, DebugInformationFormat.Pdb)) { var moduleVersionId = target.GetModuleVersionId(); var blocks = runtime.Modules.SelectAsArray(m => m.MetadataBlock); IReadOnlyDictionary<string, ImmutableArray<(AssemblyIdentity, MetadataReference)>> referencesBySimpleName; var actualReferences = blocks.MakeAssemblyReferences(moduleVersionId, CompilationExtensions.IdentityComparer, MakeAssemblyReferencesKind.DirectReferencesOnly, out referencesBySimpleName); Assert.Null(referencesBySimpleName); // Verify identities. var actualIdentities = actualReferences.SelectAsArray(r => r.GetAssemblyIdentity()); AssertEx.Equal(expectedIdentities, actualIdentities); // Verify identities are unique. var uniqueIdentities = actualIdentities.Distinct(); Assert.Equal(actualIdentities.Length, uniqueIdentities.Length); actualReferences = blocks.MakeAssemblyReferences(moduleVersionId, CompilationExtensions.IdentityComparer, MakeAssemblyReferencesKind.AllReferences, out referencesBySimpleName); Assert.Equal(2, actualReferences.Length); Assert.Equal(moduleVersionId, actualReferences[1].GetModuleVersionId()); foreach (var reference in references) { var identity = reference.GetAssemblyIdentity(); var pairs = referencesBySimpleName[identity.Name]; var other = pairs.FirstOrDefault(p => identity.Equals(p.Item1)); Assert.Equal(identity, other.Item1); } } } private static void VerifyResolutionRequests(EvaluationContext context, params (AssemblyIdentity, AssemblyIdentity, int)[] expectedRequests) { ExpressionCompilerTestHelpers.VerifyResolutionRequests( (EEMetadataReferenceResolver)context.Compilation.Options.MetadataReferenceResolver, expectedRequests); } [Fact] public void DuplicateTypesAndMethodsDifferentAssemblies() { var sourceA = @"using N; namespace N { class C1 { } public static class E { public static A F(this A o) { return o; } } } class C2 { } public class A { public static void M() { var x = new A(); var y = x.F(); } }"; var sourceB = @"using N; namespace N { class C1 { } public static class E { public static int F(this A o) { return 2; } } } class C2 { } public class B { static void M() { var x = new A(); } }"; var compilationA = CreateCompilationWithMscorlib40AndSystemCore(sourceA, options: TestOptions.DebugDll); var identityA = compilationA.Assembly.Identity; var moduleA = compilationA.ToModuleInstance(); var compilationB = CreateCompilationWithMscorlib40AndSystemCore(sourceB, options: TestOptions.DebugDll, references: new[] { moduleA.GetReference() }); var moduleB = compilationB.ToModuleInstance(); var runtime = CreateRuntimeInstance(new[] { MscorlibRef.ToModuleInstance(), SystemCoreRef.ToModuleInstance(), moduleA, moduleB }); ImmutableArray<MetadataBlock> blocks; Guid moduleVersionId; ISymUnmanagedReader symReader; int typeToken; int methodToken; int localSignatureToken; GetContextState(runtime, "B", out blocks, out moduleVersionId, out symReader, out typeToken, out localSignatureToken); string errorMessage; CompilationTestData testData; var contextFactory = CreateTypeContextFactory(moduleVersionId, typeToken); // Duplicate type in namespace, at type scope. ExpressionCompilerTestHelpers.CompileExpressionWithRetry(blocks, "new N.C1()", ImmutableArray<Alias>.Empty, contextFactory, getMetaDataBytesPtr: null, errorMessage: out errorMessage, testData: out testData); IEnumerable<string> CS0433Messages(string type) { yield return "error CS0433: " + string.Format(CSharpResources.ERR_SameFullNameAggAgg, compilationA.Assembly.Identity, type, compilationB.Assembly.Identity); yield return "error CS0433: " + string.Format(CSharpResources.ERR_SameFullNameAggAgg, compilationB.Assembly.Identity, type, compilationA.Assembly.Identity); } Assert.Contains(errorMessage, CS0433Messages("C1")); GetContextState(runtime, "B.M", out blocks, out moduleVersionId, out symReader, out methodToken, out localSignatureToken); contextFactory = CreateMethodContextFactory(moduleVersionId, symReader, methodToken, localSignatureToken); // Duplicate type in namespace, at method scope. ExpressionCompilerTestHelpers.CompileExpressionWithRetry(blocks, "new C1()", ImmutableArray<Alias>.Empty, contextFactory, getMetaDataBytesPtr: null, errorMessage: out errorMessage, testData: out testData); Assert.Contains(errorMessage, CS0433Messages("C1")); // Duplicate type in global namespace, at method scope. ExpressionCompilerTestHelpers.CompileExpressionWithRetry(blocks, "new C2()", ImmutableArray<Alias>.Empty, contextFactory, getMetaDataBytesPtr: null, errorMessage: out errorMessage, testData: out testData); Assert.Contains(errorMessage, CS0433Messages("C2")); // Duplicate extension method, at method scope. ExpressionCompilerTestHelpers.CompileExpressionWithRetry(blocks, "x.F()", ImmutableArray<Alias>.Empty, contextFactory, getMetaDataBytesPtr: null, errorMessage: out errorMessage, testData: out testData); Assert.Equal($"error CS0121: { string.Format(CSharpResources.ERR_AmbigCall, "N.E.F(A)", "N.E.F(A)") }", errorMessage); // Same tests as above but in library that does not directly reference duplicates. GetContextState(runtime, "A", out blocks, out moduleVersionId, out symReader, out typeToken, out localSignatureToken); contextFactory = CreateTypeContextFactory(moduleVersionId, typeToken); // Duplicate type in namespace, at type scope. ExpressionCompilerTestHelpers.CompileExpressionWithRetry(blocks, "new N.C1()", ImmutableArray<Alias>.Empty, contextFactory, getMetaDataBytesPtr: null, errorMessage: out errorMessage, testData: out testData); Assert.Null(errorMessage); var methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""N.C1..ctor()"" IL_0005: ret }"); Assert.Equal(((MethodSymbol)methodData.Method).ReturnType.ContainingAssembly.ToDisplayString(), identityA.GetDisplayName()); GetContextState(runtime, "A.M", out blocks, out moduleVersionId, out symReader, out methodToken, out localSignatureToken); contextFactory = CreateMethodContextFactory(moduleVersionId, symReader, methodToken, localSignatureToken); // Duplicate type in global namespace, at method scope. ExpressionCompilerTestHelpers.CompileExpressionWithRetry(blocks, "new C2()", ImmutableArray<Alias>.Empty, contextFactory, getMetaDataBytesPtr: null, errorMessage: out errorMessage, testData: out testData); Assert.Null(errorMessage); methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 6 (0x6) .maxstack 1 .locals init (A V_0, //x A V_1) //y IL_0000: newobj ""C2..ctor()"" IL_0005: ret }"); Assert.Equal(((MethodSymbol)methodData.Method).ReturnType.ContainingAssembly.ToDisplayString(), identityA.GetDisplayName()); // Duplicate extension method, at method scope. ExpressionCompilerTestHelpers.CompileExpressionWithRetry(blocks, "x.F()", ImmutableArray<Alias>.Empty, contextFactory, getMetaDataBytesPtr: null, errorMessage: out errorMessage, testData: out testData); Assert.Null(errorMessage); methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 7 (0x7) .maxstack 1 .locals init (A V_0, //x A V_1) //y IL_0000: ldloc.0 IL_0001: call ""A N.E.F(A)"" IL_0006: ret }"); Assert.Equal(((MethodSymbol)methodData.Method).ReturnType.ContainingAssembly.ToDisplayString(), identityA.GetDisplayName()); } /// <summary> /// mscorlib.dll is not directly referenced from an assembly /// compiled against portable framework assemblies. /// </summary> [WorkItem(1150981, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1150981")] [Fact] public void MissingMscorlib() { var sourceA = @"public class A { } class B { } class C { }"; var sourceB = @"public class B : A { }"; var moduleA = CreateEmptyCompilation( sourceA, references: new[] { SystemRuntimePP7Ref }, options: TestOptions.DebugDll).ToModuleInstance(); var moduleB = CreateEmptyCompilation( sourceB, references: new[] { SystemRuntimePP7Ref, moduleA.GetReference() }, options: TestOptions.DebugDll).ToModuleInstance(); // Include an empty assembly to verify that not all assemblies // with no references are treated as mscorlib. var referenceC = AssemblyMetadata.CreateFromImage(TestResources.ExpressionCompiler.Empty).GetReference(); // At runtime System.Runtime.dll contract assembly is replaced // by mscorlib.dll and System.Runtime.dll facade assemblies. var runtime = CreateRuntimeInstance(new[] { MscorlibFacadeRef.ToModuleInstance(), SystemRuntimeFacadeRef.ToModuleInstance(), moduleA, moduleB, referenceC.ToModuleInstance() }); ImmutableArray<MetadataBlock> blocks; Guid moduleVersionId; ISymUnmanagedReader symReader; int typeToken; int localSignatureToken; GetContextState(runtime, "C", out blocks, out moduleVersionId, out symReader, out typeToken, out localSignatureToken); string errorMessage; CompilationTestData testData; int attempts = 0; EvaluationContextBase contextFactory(ImmutableArray<MetadataBlock> b, bool u) { attempts++; return EvaluationContext.CreateTypeContext( ToCompilation(b, u, moduleVersionId), moduleVersionId, typeToken); } // Compile: [DebuggerDisplay("{new B()}")] const string expr = "new B()"; ExpressionCompilerTestHelpers.CompileExpressionWithRetry(blocks, expr, ImmutableArray<Alias>.Empty, contextFactory, getMetaDataBytesPtr: null, errorMessage: out errorMessage, testData: out testData); Assert.Null(errorMessage); Assert.Equal(2, attempts); var methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""B..ctor()"" IL_0005: ret }"); } [WorkItem(1170032, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1170032")] [Fact] public void DuplicateTypesInMscorlib() { var sourceConsole = @"namespace System { public class Console { } }"; var sourceObjectModel = @"namespace System.Collections.ObjectModel { public class ReadOnlyDictionary<K, V> { } }"; var source = @"class C { static void Main() { var t = typeof(System.Console); var o = (System.Collections.ObjectModel.ReadOnlyDictionary<object, object>)null; } }"; var systemConsoleComp = CreateCompilation(sourceConsole, options: TestOptions.DebugDll, assemblyName: "System.Console"); var systemConsoleRef = systemConsoleComp.EmitToImageReference(); var systemObjectModelComp = CreateCompilation(sourceObjectModel, options: TestOptions.DebugDll, assemblyName: "System.ObjectModel"); var systemObjectModelRef = systemObjectModelComp.EmitToImageReference(); var identityObjectModel = systemObjectModelRef.GetAssemblyIdentity(); // At runtime System.Runtime.dll contract assembly is replaced // by mscorlib.dll and System.Runtime.dll facade assemblies; // System.Console.dll and System.ObjectModel.dll are not replaced. // Test different ordering of modules containing duplicates: // { System.Console, mscorlib } and { mscorlib, System.ObjectModel }. var contractReferences = ImmutableArray.Create(systemConsoleRef, SystemRuntimePP7Ref, systemObjectModelRef); var runtimeReferences = ImmutableArray.Create(systemConsoleRef, MscorlibFacadeRef, SystemRuntimeFacadeRef, systemObjectModelRef); // Verify the compiler reports duplicate types with facade assemblies. var compilation = CreateEmptyCompilation( source, references: runtimeReferences, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName()); compilation.VerifyDiagnostics( // error CS0433: The type 'Console' exists in both 'System.Console, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' // var t = typeof(System.Console); Diagnostic(ErrorCode.ERR_SameFullNameAggAgg, "Console").WithArguments("System.Console, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "System.Console", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089").WithLocation(5, 31), // error CS0433: The type 'ReadOnlyDictionary<K, V>' exists in both 'System.ObjectModel, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' // var o = (System.Collections.ObjectModel.ReadOnlyDictionary<object, object>)null; Diagnostic(ErrorCode.ERR_SameFullNameAggAgg, "ReadOnlyDictionary<object, object>").WithArguments("System.ObjectModel, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "System.Collections.ObjectModel.ReadOnlyDictionary<K, V>", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089").WithLocation(6, 49)); // EE should not report duplicate type when the original source // is compiled with contract assemblies and the EE expression // is compiled with facade assemblies. compilation = CreateEmptyCompilation( source, references: contractReferences, options: TestOptions.DebugDll); WithRuntimeInstance(compilation, runtimeReferences, runtime => { var context = CreateMethodContext(runtime, "C.Main"); string errorMessage; // { System.Console, mscorlib } var testData = new CompilationTestData(); context.CompileExpression("typeof(System.Console)", out errorMessage, testData); var methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL(@" { // Code size 11 (0xb) .maxstack 1 .locals init (System.Type V_0, //t System.Collections.ObjectModel.ReadOnlyDictionary<object, object> V_1) //o IL_0000: ldtoken ""System.Console"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ret }"); // { mscorlib, System.ObjectModel } testData = new CompilationTestData(); context.CompileExpression("(System.Collections.ObjectModel.ReadOnlyDictionary<object, object>)null", out errorMessage, testData); methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL(@" { // Code size 2 (0x2) .maxstack 1 .locals init (System.Type V_0, //t System.Collections.ObjectModel.ReadOnlyDictionary<object, object> V_1) //o IL_0000: ldnull IL_0001: ret }"); Assert.Equal(((MethodSymbol)methodData.Method).ReturnType.ContainingAssembly.ToDisplayString(), identityObjectModel.GetDisplayName()); }); } /// <summary> /// Intrinsic methods assembly should not be dropped. /// </summary> [WorkItem(4140, "https://github.com/dotnet/roslyn/issues/4140")] [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] public void IntrinsicMethods() { var sourceA = @"public class A { }"; var sourceB = @"public class A { } public class B { static void M(A a) { } }"; var compilationA = CreateCompilationWithMscorlib40AndSystemCore(sourceA, options: TestOptions.DebugDll); var moduleA = compilationA.ToModuleInstance(); var compilationB = CreateCompilationWithMscorlib40AndSystemCore(sourceB, options: TestOptions.DebugDll, references: new[] { moduleA.GetReference() }); var moduleB = compilationB.ToModuleInstance(); var runtime = CreateRuntimeInstance(new[] { MscorlibRef.ToModuleInstance(), SystemCoreRef.ToModuleInstance(), moduleA, moduleB, ExpressionCompilerTestHelpers.IntrinsicAssemblyReference.ToModuleInstance() }); ImmutableArray<MetadataBlock> blocks; Guid moduleVersionId; ISymUnmanagedReader symReader; int methodToken; int localSignatureToken; GetContextState(runtime, "B.M", out blocks, out moduleVersionId, out symReader, out methodToken, out localSignatureToken); var aliases = ImmutableArray.Create( ExceptionAlias(typeof(ArgumentException)), ReturnValueAlias(2, typeof(string)), ObjectIdAlias(1, typeof(object))); int attempts = 0; EvaluationContextBase contextFactory(ImmutableArray<MetadataBlock> b, bool u) { attempts++; return EvaluationContext.CreateMethodContext( ToCompilation(b, u, moduleVersionId), symReader, moduleVersionId, methodToken, methodVersion: 1, ilOffset: 0, localSignatureToken: localSignatureToken); } string errorMessage; CompilationTestData testData; ExpressionCompilerTestHelpers.CompileExpressionWithRetry( blocks, "(object)new A() ?? $exception ?? $1 ?? $ReturnValue2", aliases, contextFactory, getMetaDataBytesPtr: null, errorMessage: out errorMessage, testData: out testData); Assert.Null(errorMessage); Assert.Equal(2, attempts); var methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 49 (0x31) .maxstack 2 IL_0000: newobj ""A..ctor()"" IL_0005: dup IL_0006: brtrue.s IL_0030 IL_0008: pop IL_0009: call ""System.Exception Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetException()"" IL_000e: castclass ""System.ArgumentException"" IL_0013: dup IL_0014: brtrue.s IL_0030 IL_0016: pop IL_0017: ldstr ""$1"" IL_001c: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_0021: dup IL_0022: brtrue.s IL_0030 IL_0024: pop IL_0025: ldc.i4.2 IL_0026: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetReturnValue(int)"" IL_002b: castclass ""string"" IL_0030: ret }"); } private const string CorLibAssemblyName = "System.Private.CoreLib"; // An assembly with the expected corlib name and with System.Object should // be considered the corlib, even with references to external assemblies. [WorkItem(13275, "https://github.com/dotnet/roslyn/issues/13275")] [WorkItem(30030, "https://github.com/dotnet/roslyn/issues/30030")] [Fact] public void CorLibWithAssemblyReferences() { string sourceLib = @"public class Private1 { } public class Private2 { }"; var compLib = CreateCompilation(sourceLib, assemblyName: "System.Private.Library"); compLib.VerifyDiagnostics(); var refLib = compLib.EmitToImageReference(); string sourceCorLib = @"using System.Runtime.CompilerServices; [assembly: TypeForwardedTo(typeof(Private2))] namespace System { public class Object { public Private1 F() => null; } #pragma warning disable 0436 public class Void : Object { } #pragma warning restore 0436 }"; // Create a custom corlib with a reference to compilation // above and a reference to the actual mscorlib. var compCorLib = CreateEmptyCompilation(sourceCorLib, assemblyName: CorLibAssemblyName, references: new[] { MscorlibRef, refLib }); compCorLib.VerifyDiagnostics(); var objectType = compCorLib.SourceAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("System.Object"); Assert.NotNull(objectType.BaseType()); ImmutableArray<byte> peBytes; ImmutableArray<byte> pdbBytes; ExpressionCompilerTestHelpers.EmitCorLibWithAssemblyReferences( compCorLib, null, (moduleBuilder, emitOptions) => new PEAssemblyBuilderWithAdditionalReferences(moduleBuilder, emitOptions, objectType.GetCciAdapter()), out peBytes, out pdbBytes); using (var reader = new PEReader(peBytes)) { var metadata = reader.GetMetadata(); var module = metadata.ToModuleMetadata(ignoreAssemblyRefs: true); var metadataReader = metadata.ToMetadataReader(); var moduleInstance = ModuleInstance.Create(metadata, metadataReader.GetModuleVersionIdOrThrow()); // Verify the module declares System.Object. Assert.True(metadataReader.DeclaresTheObjectClass()); // Verify the PEModule has no assembly references. Assert.Equal(0, module.Module.ReferencedAssemblies.Length); // Verify the underlying metadata has the expected assembly references. var actualReferences = metadataReader.AssemblyReferences.Select(r => metadataReader.GetString(metadataReader.GetAssemblyReference(r).Name)).ToImmutableArray(); AssertEx.Equal(new[] { "mscorlib", "System.Private.Library" }, actualReferences); var source = @"class C { static void M() { } }"; var comp = CreateEmptyCompilation(source, options: TestOptions.DebugDll, references: new[] { refLib, AssemblyMetadata.Create(module).GetReference() }); comp.VerifyDiagnostics(); using (var runtime = RuntimeInstance.Create(new[] { comp.ToModuleInstance(), moduleInstance })) { string error; var context = CreateMethodContext(runtime, "C.M"); // Valid expression. var testData = new CompilationTestData(); context.CompileExpression( "new object()", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""object..ctor()"" IL_0005: ret }"); // Invalid expression: System.Int32 is not defined in corlib above. testData = new CompilationTestData(); context.CompileExpression( "1", out error, testData); Assert.Equal("error CS0518: Predefined type 'System.Int32' is not defined or imported", error); // Invalid expression: type in method signature from missing referenced assembly. testData = new CompilationTestData(); context.CompileExpression( "(new object()).F()", out error, testData); Assert.Equal("error CS0570: 'object.F()' is not supported by the language", error); // Invalid expression: type forwarded to missing referenced assembly. testData = new CompilationTestData(); context.CompileExpression( "new Private2()", out error, testData); Assert.Equal("error CS0246: The type or namespace name 'Private2' could not be found (are you missing a using directive or an assembly reference?)", error); } } } // References to missing assembly from PDB custom debug info. [WorkItem(13275, "https://github.com/dotnet/roslyn/issues/13275")] [Theory] [MemberData(nameof(NonNullTypesTrueAndFalseReleaseDll))] public void CorLibWithAssemblyReferences_Pdb(CSharpCompilationOptions options) { string sourceLib = @"namespace Namespace { public class Private { } }"; var compLib = CreateCompilation(sourceLib, assemblyName: "System.Private.Library"); compLib.VerifyDiagnostics(); var refLib = compLib.EmitToImageReference(aliases: ImmutableArray.Create("A")); string sourceCorLib = @"extern alias A; #pragma warning disable 8019 using N = A::Namespace; namespace System { public class Object { public void F() { } } #pragma warning disable 0436 public class Void : Object { } #pragma warning restore 0436 }"; // Create a custom corlib with a reference to compilation // above and a reference to the actual mscorlib. var compCorLib = CreateEmptyCompilation(sourceCorLib, assemblyName: CorLibAssemblyName, references: new[] { MscorlibRef, refLib }, options: options); compCorLib.VerifyDiagnostics(); var objectType = compCorLib.SourceAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("System.Object"); Assert.NotNull(objectType.BaseType()); var pdbPath = Temp.CreateDirectory().Path; ImmutableArray<byte> peBytes; ImmutableArray<byte> pdbBytes; ExpressionCompilerTestHelpers.EmitCorLibWithAssemblyReferences( compCorLib, pdbPath, (moduleBuilder, emitOptions) => new PEAssemblyBuilderWithAdditionalReferences(moduleBuilder, emitOptions, objectType.GetCciAdapter()), out peBytes, out pdbBytes); var symReader = SymReaderFactory.CreateReader(pdbBytes); using (var reader = new PEReader(peBytes)) { var metadata = reader.GetMetadata(); var module = metadata.ToModuleMetadata(ignoreAssemblyRefs: true); var metadataReader = metadata.ToMetadataReader(); var moduleInstance = ModuleInstance.Create(metadata, metadataReader.GetModuleVersionIdOrThrow(), symReader); // Verify the module declares System.Object. Assert.True(metadataReader.DeclaresTheObjectClass()); // Verify the PEModule has no assembly references. Assert.Equal(0, module.Module.ReferencedAssemblies.Length); // Verify the underlying metadata has the expected assembly references. var actualReferences = metadataReader.AssemblyReferences.Select(r => metadataReader.GetString(metadataReader.GetAssemblyReference(r).Name)).ToImmutableArray(); AssertEx.Equal(new[] { "mscorlib", "System.Private.Library" }, actualReferences); using (var runtime = RuntimeInstance.Create(new[] { moduleInstance })) { string error; var context = CreateMethodContext(runtime, "System.Object.F"); var testData = new CompilationTestData(); // Invalid import: "using N = A::Namespace;". context.CompileExpression( "new N.Private()", out error, testData); Assert.Equal("error CS0246: The type or namespace name 'N' could not be found (are you missing a using directive or an assembly reference?)", error); } } } // An assembly with the expected corlib name but without // System.Object should not be considered the corlib. [Fact] public void CorLibWithAssemblyReferencesNoSystemObject() { // Assembly with expected corlib name but without System.Object declared. string sourceLib = @"class Private { }"; var compLib = CreateCompilation(sourceLib, assemblyName: CorLibAssemblyName); compLib.VerifyDiagnostics(); var refLib = compLib.EmitToImageReference(); var source = @"class C { static void M() { } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics(); using (var runtime = RuntimeInstance.Create(new[] { comp.ToModuleInstance(), refLib.ToModuleInstance(), MscorlibRef.ToModuleInstance() })) { string error; var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); context.CompileExpression( "1.GetType()", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 12 (0xc) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: call ""System.Type object.GetType()"" IL_000b: ret }"); } } private static ExpressionCompiler.CreateContextDelegate CreateTypeContextFactory( Guid moduleVersionId, int typeToken) { return (blocks, useReferencedModulesOnly) => EvaluationContext.CreateTypeContext( ToCompilation(blocks, useReferencedModulesOnly, moduleVersionId), moduleVersionId, typeToken); } private static ExpressionCompiler.CreateContextDelegate CreateMethodContextFactory( Guid moduleVersionId, ISymUnmanagedReader symReader, int methodToken, int localSignatureToken) { return (blocks, useReferencedModulesOnly) => EvaluationContext.CreateMethodContext( ToCompilation(blocks, useReferencedModulesOnly, moduleVersionId), symReader, moduleVersionId, methodToken, methodVersion: 1, ilOffset: 0, localSignatureToken: localSignatureToken); } private static CSharpCompilation ToCompilation( ImmutableArray<MetadataBlock> blocks, bool useReferencedModulesOnly, Guid moduleVersionId) { return blocks.ToCompilation(moduleVersionId, useReferencedModulesOnly ? MakeAssemblyReferencesKind.DirectReferencesOnly : MakeAssemblyReferencesKind.AllAssemblies); } private sealed class PEAssemblyBuilderWithAdditionalReferences : PEModuleBuilder, IAssemblyReference { private readonly CommonPEModuleBuilder _builder; private readonly NamespaceTypeDefinitionNoBase _objectType; internal PEAssemblyBuilderWithAdditionalReferences(CommonPEModuleBuilder builder, EmitOptions emitOptions, INamespaceTypeDefinition objectType) : base((SourceModuleSymbol)builder.CommonSourceModule, emitOptions, builder.OutputKind, builder.SerializationProperties, builder.ManifestResources) { _builder = builder; _objectType = new NamespaceTypeDefinitionNoBase(objectType); } public override IEnumerable<INamespaceTypeDefinition> GetTopLevelSourceTypeDefinitions(EmitContext context) { foreach (var type in base.GetTopLevelSourceTypeDefinitions(context)) { yield return (type == _objectType.UnderlyingType) ? _objectType : type; } } public override SymbolChanges EncSymbolChanges => _builder.EncSymbolChanges; public override EmitBaseline PreviousGeneration => _builder.PreviousGeneration; public override ISourceAssemblySymbolInternal SourceAssemblyOpt => _builder.SourceAssemblyOpt; public override IEnumerable<IFileReference> GetFiles(EmitContext context) => _builder.GetFiles(context); protected override void AddEmbeddedResourcesFromAddedModules(ArrayBuilder<ManagedResource> builder, DiagnosticBag diagnostics) { } internal override SynthesizedAttributeData SynthesizeEmbeddedAttribute() { throw new NotImplementedException(); } AssemblyIdentity IAssemblyReference.Identity => ((IAssemblyReference)_builder).Identity; Version IAssemblyReference.AssemblyVersionPattern => ((IAssemblyReference)_builder).AssemblyVersionPattern; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Reflection.PortableExecutable; using Microsoft.Cci; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.DiaSymReader; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.PdbUtilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class ReferencedModulesTests : ExpressionCompilerTestBase { /// <summary> /// MakeAssemblyReferences should drop unreferenced assemblies. /// </summary> [Fact] public void UnreferencedAssemblies() { var (identityMscorlib, moduleMscorlib) = (MscorlibRef.GetAssemblyIdentity(), MscorlibRef.ToModuleInstance()); var (identityIntrinsic, moduleIntrinsic) = (ExpressionCompilerTestHelpers.IntrinsicAssemblyReference.GetAssemblyIdentity(), ExpressionCompilerTestHelpers.IntrinsicAssemblyReference.ToModuleInstance()); var (identityA1, moduleA1, refA1) = Compile("A1", "public class A1 { static void M() { } }"); var (identityA2, moduleA2, refA2) = Compile("A2", "public class A2 { static void M() { } }"); var (identityB1, moduleB1, refB1) = Compile("B1", "public class B1 : A1 { static void M() { } }", refA1); var (identityB2, moduleB2, refB2) = Compile("B2", "public class B2 : A1 { static void M() { } }", refA1); var (identityC, moduleC, refC) = Compile("C", "public class C1 : B2 { static void M() { } } public class C2 : A2 { }", refA1, refA2, refB2); using (var runtime = CreateRuntimeInstance(new[] { moduleMscorlib, moduleA1, moduleA2, moduleB1, moduleB2, moduleC })) { var stateB2 = GetContextState(runtime, "B2.M"); // B2.M with missing A1. var context = CreateMethodContext( new AppDomain(), ImmutableArray.Create(moduleMscorlib, moduleA2, moduleB1, moduleB2, moduleC).SelectAsArray(m => m.MetadataBlock), stateB2); ResultProperties resultProperties; string error; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; context.CompileExpression("new B2()", DkmEvaluationFlags.TreatAsExpression, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData: null); Assert.Equal("error CS0012: The type 'A1' is defined in an assembly that is not referenced. You must add a reference to assembly 'A1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.", error); AssertEx.Equal(new[] { identityA1 }, missingAssemblyIdentities); VerifyResolutionRequests(context, (identityA1, null, 1)); // B2.M with all assemblies. context = CreateMethodContext( new AppDomain(), ImmutableArray.Create(moduleMscorlib, moduleA1, moduleA2, moduleB1, moduleB2, moduleC).SelectAsArray(m => m.MetadataBlock), stateB2); var testData = new CompilationTestData(); context.CompileExpression("new B2()", out error, testData); var methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""B2..ctor()"" IL_0005: ret }"); VerifyResolutionRequests(context, (identityA1, identityA1, 1)); // B2.M with all assemblies in reverse order. context = CreateMethodContext( new AppDomain(), ImmutableArray.Create(moduleC, moduleB2, moduleB1, moduleA2, moduleA1, moduleMscorlib, moduleIntrinsic).SelectAsArray(m => m.MetadataBlock), stateB2); testData = new CompilationTestData(); context.CompileExpression("new B2()", out error, testData); methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""B2..ctor()"" IL_0005: ret }"); VerifyResolutionRequests(context, (identityA1, identityA1, 1)); // A1.M with all assemblies. var stateA1 = GetContextState(runtime, "A1.M"); context = CreateMethodContext( new AppDomain(), ImmutableArray.Create(moduleMscorlib, moduleA1, moduleA2, moduleB1, moduleB2, moduleC).SelectAsArray(m => m.MetadataBlock), stateA1); testData = new CompilationTestData(); context.CompileExpression("new A1()", out error, testData); methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""A1..ctor()"" IL_0005: ret }"); VerifyResolutionRequests(context); // B1.M with all assemblies. var stateB1 = GetContextState(runtime, "B1.M"); context = CreateMethodContext( new AppDomain(), ImmutableArray.Create(moduleMscorlib, moduleA1, moduleA2, moduleB1, moduleB2, moduleC).SelectAsArray(m => m.MetadataBlock), stateB1); testData = new CompilationTestData(); context.CompileExpression("new B1()", out error, testData); methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""B1..ctor()"" IL_0005: ret }"); VerifyResolutionRequests(context, (identityA1, identityA1, 1)); // C1.M with all assemblies. var stateC = GetContextState(runtime, "C1.M"); context = CreateMethodContext( new AppDomain(), ImmutableArray.Create(moduleMscorlib, moduleA1, moduleA2, moduleB1, moduleB2, moduleC).SelectAsArray(m => m.MetadataBlock), stateC); testData = new CompilationTestData(); context.CompileExpression("new C1()", out error, testData); methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""C1..ctor()"" IL_0005: ret }"); VerifyResolutionRequests(context, (identityB2, identityB2, 1), (identityA1, identityA1, 1), (identityA2, identityA2, 1)); // Other EvaluationContext.CreateMethodContext overload. // A1.M with all assemblies. var allBlocks = ImmutableArray.Create(moduleMscorlib, moduleA1, moduleA2, moduleB1, moduleB2, moduleC).SelectAsArray(m => m.MetadataBlock); context = EvaluationContext.CreateMethodContext( allBlocks, stateA1.SymReader, stateA1.ModuleVersionId, stateA1.MethodToken, methodVersion: 1, stateA1.ILOffset, stateA1.LocalSignatureToken); testData = new CompilationTestData(); context.CompileExpression("new B1()", out error, testData); methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""B1..ctor()"" IL_0005: ret }"); // Other EvaluationContext.CreateMethodContext overload. // A1.M with all assemblies, offset outside of IL. context = EvaluationContext.CreateMethodContext( allBlocks, stateA1.SymReader, stateA1.ModuleVersionId, stateA1.MethodToken, methodVersion: 1, uint.MaxValue, stateA1.LocalSignatureToken); testData = new CompilationTestData(); context.CompileExpression("new C1()", out error, testData); methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""C1..ctor()"" IL_0005: ret }"); } } [Fact] public void DifferentAssemblyVersions() { var publicKeyA = ImmutableArray.CreateRange(new byte[] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00, 0x06, 0x02, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x52, 0x53, 0x41, 0x31, 0x00, 0x04, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0xED, 0xD3, 0x22, 0xCB, 0x6B, 0xF8, 0xD4, 0xA2, 0xFC, 0xCC, 0x87, 0x37, 0x04, 0x06, 0x04, 0xCE, 0xE7, 0xB2, 0xA6, 0xF8, 0x4A, 0xEE, 0xF3, 0x19, 0xDF, 0x5B, 0x95, 0xE3, 0x7A, 0x6A, 0x28, 0x24, 0xA4, 0x0A, 0x83, 0x83, 0xBD, 0xBA, 0xF2, 0xF2, 0x52, 0x20, 0xE9, 0xAA, 0x3B, 0xD1, 0xDD, 0xE4, 0x9A, 0x9A, 0x9C, 0xC0, 0x30, 0x8F, 0x01, 0x40, 0x06, 0xE0, 0x2B, 0x95, 0x62, 0x89, 0x2A, 0x34, 0x75, 0x22, 0x68, 0x64, 0x6E, 0x7C, 0x2E, 0x83, 0x50, 0x5A, 0xCE, 0x7B, 0x0B, 0xE8, 0xF8, 0x71, 0xE6, 0xF7, 0x73, 0x8E, 0xEB, 0x84, 0xD2, 0x73, 0x5D, 0x9D, 0xBE, 0x5E, 0xF5, 0x90, 0xF9, 0xAB, 0x0A, 0x10, 0x7E, 0x23, 0x48, 0xF4, 0xAD, 0x70, 0x2E, 0xF7, 0xD4, 0x51, 0xD5, 0x8B, 0x3A, 0xF7, 0xCA, 0x90, 0x4C, 0xDC, 0x80, 0x19, 0x26, 0x65, 0xC9, 0x37, 0xBD, 0x52, 0x81, 0xF1, 0x8B, 0xCD }); var options = TestOptions.DebugDll.WithDelaySign(true); var (identityMscorlib, moduleMscorlib) = (MscorlibRef.GetAssemblyIdentity(), MscorlibRef.ToModuleInstance()); var (identityA1, moduleA1, refA1) = Compile(new AssemblyIdentity("A", new Version(1, 1, 1, 1), publicKeyOrToken: publicKeyA, hasPublicKey: true), "public class A { }", options, MscorlibRef); var (identityA2, moduleA2, refA2) = Compile(new AssemblyIdentity("A", new Version(2, 2, 2, 2), publicKeyOrToken: publicKeyA, hasPublicKey: true), "public class A { }", options, MscorlibRef); var (identityA3, moduleA3, refA3) = Compile(new AssemblyIdentity("a", new Version(3, 3, 3, 3), publicKeyOrToken: publicKeyA, hasPublicKey: true), "public class A { }", options, MscorlibRef); var (identityB1, moduleB1, refB1) = Compile(new AssemblyIdentity("B", new Version(1, 1, 1, 1)), "public class B : A { static void M() { } }", TestOptions.DebugDll, refA2, MscorlibRef); using (var runtime = CreateRuntimeInstance(new[] { moduleMscorlib, moduleA1, moduleA2, moduleA3, moduleB1 })) { var stateB = GetContextState(runtime, "B.M"); // Expected version of A. var context = CreateMethodContext( new AppDomain(), ImmutableArray.Create(moduleMscorlib, moduleA2, moduleB1).SelectAsArray(m => m.MetadataBlock), stateB); string error; var testData = new CompilationTestData(); context.CompileExpression("new B()", out error, testData); var methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""B..ctor()"" IL_0005: ret }"); VerifyResolutionRequests(context, (identityA2, identityA2, 1)); // Higher version of A. context = CreateMethodContext( new AppDomain(), ImmutableArray.Create(moduleMscorlib, moduleA3, moduleB1).SelectAsArray(m => m.MetadataBlock), stateB); testData = new CompilationTestData(); context.CompileExpression("new B()", out error, testData); methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""B..ctor()"" IL_0005: ret }"); VerifyResolutionRequests(context, (identityA2, identityA3, 1)); // Lower version of A. context = CreateMethodContext( new AppDomain(), ImmutableArray.Create(moduleMscorlib, moduleA1, moduleB1).SelectAsArray(m => m.MetadataBlock), stateB); testData = new CompilationTestData(); context.CompileExpression("new B()", out error, testData); Assert.Equal("error CS1705: Assembly 'B' with identity 'B, Version=1.1.1.1, Culture=neutral, PublicKeyToken=null' uses 'A, Version=2.2.2.2, Culture=neutral, PublicKeyToken=1f8a32457d187bf3' which has a higher version than referenced assembly 'A' with identity 'A, Version=1.1.1.1, Culture=neutral, PublicKeyToken=1f8a32457d187bf3'", error); VerifyResolutionRequests(context, (identityA2, identityA1, 1)); // Multiple versions of A. context = CreateMethodContext( new AppDomain(), ImmutableArray.Create(moduleMscorlib, moduleA1, moduleA3, moduleA2, moduleB1).SelectAsArray(m => m.MetadataBlock), stateB); testData = new CompilationTestData(); context.CompileExpression("new B()", out error, testData); methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""B..ctor()"" IL_0005: ret }"); VerifyResolutionRequests(context, (identityA2, identityA2, 1)); // Duplicate versions of A. context = CreateMethodContext( new AppDomain(), ImmutableArray.Create(moduleMscorlib, moduleA3, moduleA1, moduleA3, moduleA1, moduleB1).SelectAsArray(m => m.MetadataBlock), stateB); testData = new CompilationTestData(); context.CompileExpression("new B()", out error, testData); methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""B..ctor()"" IL_0005: ret }"); VerifyResolutionRequests(context, (identityA2, identityA3, 1)); } } // Not handling duplicate corlib when using referenced assemblies // only (bug #...). [Fact(Skip = "TODO")] public void DuplicateNamedCorLib() { var publicKeyOther = ImmutableArray.CreateRange(new byte[] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00, 0x06, 0x02, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x52, 0x53, 0x41, 0x31, 0x00, 0x04, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0xED, 0xD3, 0x22, 0xCB, 0x6B, 0xF8, 0xD4, 0xA2, 0xFC, 0xCC, 0x87, 0x37, 0x04, 0x06, 0x04, 0xCE, 0xE7, 0xB2, 0xA6, 0xF8, 0x4A, 0xEE, 0xF3, 0x19, 0xDF, 0x5B, 0x95, 0xE3, 0x7A, 0x6A, 0x28, 0x24, 0xA4, 0x0A, 0x83, 0x83, 0xBD, 0xBA, 0xF2, 0xF2, 0x52, 0x20, 0xE9, 0xAA, 0x3B, 0xD1, 0xDD, 0xE4, 0x9A, 0x9A, 0x9C, 0xC0, 0x30, 0x8F, 0x01, 0x40, 0x06, 0xE0, 0x2B, 0x95, 0x62, 0x89, 0x2A, 0x34, 0x75, 0x22, 0x68, 0x64, 0x6E, 0x7C, 0x2E, 0x83, 0x50, 0x5A, 0xCE, 0x7B, 0x0B, 0xE8, 0xF8, 0x71, 0xE6, 0xF7, 0x73, 0x8E, 0xEB, 0x84, 0xD2, 0x73, 0x5D, 0x9D, 0xBE, 0x5E, 0xF5, 0x90, 0xF9, 0xAB, 0x0A, 0x10, 0x7E, 0x23, 0x48, 0xF4, 0xAD, 0x70, 0x2E, 0xF7, 0xD4, 0x51, 0xD5, 0x8B, 0x3A, 0xF7, 0xCA, 0x90, 0x4C, 0xDC, 0x80, 0x19, 0x26, 0x65, 0xC9, 0x37, 0xBD, 0x52, 0x81, 0xF1, 0x8B, 0xCD }); var options = TestOptions.DebugDll.WithDelaySign(true); var (identityMscorlib, moduleMscorlib) = (MscorlibRef.GetAssemblyIdentity(), MscorlibRef.ToModuleInstance()); var (identityOther, moduleOther, refOther) = Compile(new AssemblyIdentity(identityMscorlib.Name, new Version(1, 1, 1, 1), publicKeyOrToken: publicKeyOther, hasPublicKey: true), "class Other { }", options, MscorlibRef); var (identityA, moduleA, refA) = Compile(new AssemblyIdentity("A", new Version(1, 1, 1, 1)), "public class A { }", TestOptions.DebugDll, refOther, MscorlibRef); var (identityB, moduleB, refB) = Compile(new AssemblyIdentity("B", new Version(1, 1, 1, 1)), "public class B : A { static void M() { } }", TestOptions.DebugDll, refA, refOther, MscorlibRef); using (var runtime = CreateRuntimeInstance(new[] { moduleMscorlib, moduleA, moduleB })) { var stateB = GetContextState(runtime, "B.M"); var (moduleVersionId, symReader, methodToken, localSignatureToken, ilOffset) = GetContextState(runtime, "B.M"); var context = CreateMethodContext( new AppDomain(), ImmutableArray.Create(moduleMscorlib, moduleOther, moduleA, moduleB).SelectAsArray(m => m.MetadataBlock), stateB); string error; var testData = new CompilationTestData(); context.CompileExpression("new B()", out error, testData); var methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""B..ctor()"" IL_0005: ret }"); VerifyResolutionRequests(context, (identityA, identityA, 1)); context = CreateMethodContext( new AppDomain(), ImmutableArray.Create(moduleB, moduleA, moduleOther, moduleMscorlib).SelectAsArray(m => m.MetadataBlock), stateB); testData = new CompilationTestData(); context.CompileExpression("new B()", out error, testData); methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""B..ctor()"" IL_0005: ret }"); VerifyResolutionRequests(context, (identityA, identityA, 1)); } } /// <summary> /// Reuse compilation across evaluations unless current assembly changes. /// </summary> [Fact] public void ReuseCompilation() { var (identityMscorlib, moduleMscorlib) = (MscorlibRef.GetAssemblyIdentity(), MscorlibRef.ToModuleInstance()); var (identityA1, moduleA1, refA1) = Compile("A1", "public class A1 { static void M() { } }"); var (identityA2, moduleA2, refA2) = Compile("A2", "public class A2 { static void M() { } } public class A3 { static void M() { } }"); var (identityB1, moduleB1, refB1) = Compile("B1", "public class B1 : A1 { static void M() { } } public class B2 { static void M() { } }", refA1); using (var runtime = CreateRuntimeInstance(new[] { moduleMscorlib, moduleA1, moduleA2, moduleB1 })) { var blocks = runtime.Modules.SelectAsArray(m => m.MetadataBlock); var stateA1 = GetContextState(runtime, "A1.M"); var stateA2 = GetContextState(runtime, "A2.M"); var stateA3 = GetContextState(runtime, "A3.M"); var stateB1 = GetContextState(runtime, "B1.M"); var stateB2 = GetContextState(runtime, "B2.M"); var mvidA1 = stateA1.ModuleVersionId; var mvidA2 = stateA2.ModuleVersionId; var mvidB1 = stateB1.ModuleVersionId; Assert.Equal(mvidB1, stateB2.ModuleVersionId); EvaluationContext context; MetadataContext<CSharpMetadataContext> previous; // B1 -> B2 -> A1 -> A2 -> A3 // B1.M: var appDomain = new AppDomain(); previous = appDomain.GetMetadataContext(); context = CreateMethodContext(appDomain, blocks, stateB1); VerifyResolutionRequests(context, (identityA1, identityA1, 1)); VerifyAppDomainMetadataContext(appDomain, mvidB1); // B2.M: previous = appDomain.GetMetadataContext(); context = CreateMethodContext(appDomain, blocks, stateB2); Assert.NotSame(context, GetMetadataContext(previous, mvidB1).EvaluationContext); Assert.Same(context.Compilation, GetMetadataContext(previous, mvidB1).Compilation); VerifyResolutionRequests(context, (identityA1, identityA1, 1)); VerifyAppDomainMetadataContext(appDomain, mvidB1); // A1.M: previous = appDomain.GetMetadataContext(); context = CreateMethodContext(appDomain, blocks, stateA1); Assert.NotSame(context, GetMetadataContext(previous, mvidB1).EvaluationContext); Assert.NotSame(context.Compilation, GetMetadataContext(previous, mvidB1).Compilation); VerifyResolutionRequests(context); VerifyAppDomainMetadataContext(appDomain, mvidB1, mvidA1); // A2.M: previous = appDomain.GetMetadataContext(); context = CreateMethodContext(appDomain, blocks, stateA2); Assert.NotSame(context, GetMetadataContext(previous, mvidA1).EvaluationContext); Assert.NotSame(context.Compilation, GetMetadataContext(previous, mvidA1).Compilation); VerifyResolutionRequests(context); VerifyAppDomainMetadataContext(appDomain, mvidB1, mvidA1, mvidA2); // A3.M: previous = appDomain.GetMetadataContext(); context = CreateMethodContext(appDomain, blocks, stateA3); Assert.NotSame(context, GetMetadataContext(previous, mvidA2).EvaluationContext); Assert.Same(context.Compilation, GetMetadataContext(previous, mvidA2).Compilation); VerifyResolutionRequests(context); VerifyAppDomainMetadataContext(appDomain, mvidB1, mvidA1, mvidA2); // A1 -> A2 -> A3 -> B1 -> B2 // A1.M: appDomain = new AppDomain(); context = CreateMethodContext(appDomain, blocks, stateA1); VerifyResolutionRequests(context); VerifyAppDomainMetadataContext(appDomain, mvidA1); // A2.M: previous = appDomain.GetMetadataContext(); context = CreateMethodContext(appDomain, blocks, stateA2); Assert.NotSame(context, GetMetadataContext(previous, mvidA1).EvaluationContext); Assert.NotSame(context.Compilation, GetMetadataContext(previous, mvidA1).Compilation); VerifyResolutionRequests(context); VerifyAppDomainMetadataContext(appDomain, mvidA1, mvidA2); // A3.M: previous = appDomain.GetMetadataContext(); context = CreateMethodContext(appDomain, blocks, stateA3); Assert.NotSame(context, GetMetadataContext(previous, mvidA2).EvaluationContext); Assert.Same(context.Compilation, GetMetadataContext(previous, mvidA2).Compilation); VerifyResolutionRequests(context); VerifyAppDomainMetadataContext(appDomain, mvidA1, mvidA2); // B1.M: previous = appDomain.GetMetadataContext(); context = CreateMethodContext(appDomain, blocks, stateB1); Assert.NotSame(context, GetMetadataContext(previous, mvidA2).EvaluationContext); Assert.NotSame(context.Compilation, GetMetadataContext(previous, mvidA2).Compilation); VerifyResolutionRequests(context, (identityA1, identityA1, 1)); VerifyAppDomainMetadataContext(appDomain, mvidA1, mvidA2, mvidB1); // B2.M: previous = appDomain.GetMetadataContext(); context = CreateMethodContext(appDomain, blocks, stateB2); Assert.NotSame(context, GetMetadataContext(previous, mvidB1).EvaluationContext); Assert.Same(context.Compilation, GetMetadataContext(previous, mvidB1).Compilation); VerifyResolutionRequests(context, (identityA1, identityA1, 1)); VerifyAppDomainMetadataContext(appDomain, mvidA1, mvidA2, mvidB1); } } private static void VerifyAppDomainMetadataContext(AppDomain appDomain, params Guid[] moduleVersionIds) { ExpressionCompilerTestHelpers.VerifyAppDomainMetadataContext(appDomain.GetMetadataContext(), moduleVersionIds); } [WorkItem(26159, "https://github.com/dotnet/roslyn/issues/26159")] [Fact] public void TypeOutsideAssemblyReferences() { var sourceA = @"public class A { void M() { } }"; var sourceB = @"#pragma warning disable 169 class B : A { object F; }"; var (identityMscorlib, moduleMscorlib) = (MscorlibRef.GetAssemblyIdentity(), MscorlibRef.ToModuleInstance()); var (identityA, moduleA, refA) = Compile("A", sourceA); var (identityB, moduleB, refB) = Compile("B", sourceB, refA); using (var runtime = CreateRuntimeInstance(new[] { moduleMscorlib, moduleA, moduleB })) { var blocks = runtime.Modules.SelectAsArray(m => m.MetadataBlock); var stateA = GetContextState(runtime, "A.M"); const string expr = "((B)this).F"; // A.M, all assemblies var context = CreateMethodContext(new AppDomain(), blocks, stateA, MakeAssemblyReferencesKind.AllAssemblies); string error; var testData = new CompilationTestData(); context.CompileExpression(expr, out error, testData); var methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: castclass ""B"" IL_0006: ldfld ""object B.F"" IL_000b: ret }"); // A.M, all referenced assemblies context = CreateMethodContext(new AppDomain(), blocks, stateA, MakeAssemblyReferencesKind.AllReferences); testData = new CompilationTestData(); context.CompileExpression(expr, out error, testData); Assert.Equal("error CS0246: The type or namespace name 'B' could not be found (are you missing a using directive or an assembly reference?)", error); } } [WorkItem(1141029, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1141029")] [Fact] public void AssemblyDuplicateReferences() { var sourceA = @"public class A { }"; var sourceB = @"public class B { public A F = new A(); }"; var sourceC = @"class C { private B F = new B(); static void M() { } }"; // Assembly A, multiple versions, strong name. var assemblyNameA = ExpressionCompilerUtilities.GenerateUniqueName(); var publicKeyA = ImmutableArray.CreateRange(new byte[] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00, 0x06, 0x02, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x52, 0x53, 0x41, 0x31, 0x00, 0x04, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0xED, 0xD3, 0x22, 0xCB, 0x6B, 0xF8, 0xD4, 0xA2, 0xFC, 0xCC, 0x87, 0x37, 0x04, 0x06, 0x04, 0xCE, 0xE7, 0xB2, 0xA6, 0xF8, 0x4A, 0xEE, 0xF3, 0x19, 0xDF, 0x5B, 0x95, 0xE3, 0x7A, 0x6A, 0x28, 0x24, 0xA4, 0x0A, 0x83, 0x83, 0xBD, 0xBA, 0xF2, 0xF2, 0x52, 0x20, 0xE9, 0xAA, 0x3B, 0xD1, 0xDD, 0xE4, 0x9A, 0x9A, 0x9C, 0xC0, 0x30, 0x8F, 0x01, 0x40, 0x06, 0xE0, 0x2B, 0x95, 0x62, 0x89, 0x2A, 0x34, 0x75, 0x22, 0x68, 0x64, 0x6E, 0x7C, 0x2E, 0x83, 0x50, 0x5A, 0xCE, 0x7B, 0x0B, 0xE8, 0xF8, 0x71, 0xE6, 0xF7, 0x73, 0x8E, 0xEB, 0x84, 0xD2, 0x73, 0x5D, 0x9D, 0xBE, 0x5E, 0xF5, 0x90, 0xF9, 0xAB, 0x0A, 0x10, 0x7E, 0x23, 0x48, 0xF4, 0xAD, 0x70, 0x2E, 0xF7, 0xD4, 0x51, 0xD5, 0x8B, 0x3A, 0xF7, 0xCA, 0x90, 0x4C, 0xDC, 0x80, 0x19, 0x26, 0x65, 0xC9, 0x37, 0xBD, 0x52, 0x81, 0xF1, 0x8B, 0xCD }); var compilationAS1 = CreateCompilation( new AssemblyIdentity(assemblyNameA, new Version(1, 1, 1, 1), cultureName: "", publicKeyOrToken: publicKeyA, hasPublicKey: true), new[] { sourceA }, references: new[] { MscorlibRef }, options: TestOptions.DebugDll.WithDelaySign(true)); var referenceAS1 = compilationAS1.EmitToImageReference(); var identityAS1 = referenceAS1.GetAssemblyIdentity(); var compilationAS2 = CreateCompilation( new AssemblyIdentity(assemblyNameA, new Version(2, 1, 1, 1), cultureName: "", publicKeyOrToken: publicKeyA, hasPublicKey: true), new[] { sourceA }, references: new[] { MscorlibRef }, options: TestOptions.DebugDll.WithDelaySign(true)); var referenceAS2 = compilationAS2.EmitToImageReference(); var identityAS2 = referenceAS2.GetAssemblyIdentity(); // Assembly B, multiple versions, not strong name. var assemblyNameB = ExpressionCompilerUtilities.GenerateUniqueName(); var compilationBN1 = CreateCompilation( new AssemblyIdentity(assemblyNameB, new Version(1, 1, 1, 1)), new[] { sourceB }, references: new[] { MscorlibRef, referenceAS1 }, options: TestOptions.DebugDll); var referenceBN1 = compilationBN1.EmitToImageReference(); var identityBN1 = referenceBN1.GetAssemblyIdentity(); var compilationBN2 = CreateCompilation( new AssemblyIdentity(assemblyNameB, new Version(2, 2, 2, 1)), new[] { sourceB }, references: new[] { MscorlibRef, referenceAS1 }, options: TestOptions.DebugDll); var referenceBN2 = compilationBN2.EmitToImageReference(); var identityBN2 = referenceBN2.GetAssemblyIdentity(); // Assembly B, multiple versions, strong name. var publicKeyB = ImmutableArray.CreateRange(new byte[] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00, 0x06, 0x02, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x53, 0x52, 0x41, 0x31, 0x00, 0x04, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0xED, 0xD3, 0x22, 0xCB, 0x6B, 0xF8, 0xD4, 0xA2, 0xFC, 0xCC, 0x87, 0x37, 0x04, 0x06, 0x04, 0xCE, 0xE7, 0xB2, 0xA6, 0xF8, 0x4A, 0xEE, 0xF3, 0x19, 0xDF, 0x5B, 0x95, 0xE3, 0x7A, 0x6A, 0x28, 0x24, 0xA4, 0x0A, 0x83, 0x83, 0xBD, 0xBA, 0xF2, 0xF2, 0x52, 0x20, 0xE9, 0xAA, 0x3B, 0xD1, 0xDD, 0xE4, 0x9A, 0x9A, 0x9C, 0xC0, 0x30, 0x8F, 0x01, 0x40, 0x06, 0xE0, 0x2B, 0x95, 0x62, 0x89, 0x2A, 0x34, 0x75, 0x22, 0x68, 0x64, 0x6E, 0x7C, 0x2E, 0x83, 0x50, 0x5A, 0xCE, 0x7B, 0x0B, 0xE8, 0xF8, 0x71, 0xE6, 0xF7, 0x73, 0x8E, 0xEB, 0x84, 0xD2, 0x73, 0x5D, 0x9D, 0xBE, 0x5E, 0xF5, 0x90, 0xF9, 0xAB, 0x0A, 0x10, 0x7E, 0x23, 0x48, 0xF4, 0xAD, 0x70, 0x2E, 0xF7, 0xD4, 0x51, 0xD5, 0x8B, 0x3A, 0xF7, 0xCA, 0x90, 0x4C, 0xDC, 0x80, 0x19, 0x26, 0x65, 0xC9, 0x37, 0xBD, 0x52, 0x81, 0xF1, 0x8B, 0xCD }); var compilationBS1 = CreateCompilation( new AssemblyIdentity(assemblyNameB, new Version(1, 1, 1, 1), cultureName: "", publicKeyOrToken: publicKeyB, hasPublicKey: true), new[] { sourceB }, references: new[] { MscorlibRef, referenceAS1 }, options: TestOptions.DebugDll.WithDelaySign(true)); var referenceBS1 = compilationBS1.EmitToImageReference(); var identityBS1 = referenceBS1.GetAssemblyIdentity(); var compilationBS2 = CreateCompilation( new AssemblyIdentity(assemblyNameB, new Version(2, 2, 2, 1), cultureName: "", publicKeyOrToken: publicKeyB, hasPublicKey: true), new[] { sourceB }, references: new[] { MscorlibRef, referenceAS2 }, options: TestOptions.DebugDll.WithDelaySign(true)); var referenceBS2 = compilationBS2.EmitToImageReference(); var identityBS2 = referenceBS2.GetAssemblyIdentity(); var mscorlibIdentity = MscorlibRef.GetAssemblyIdentity(); var mscorlib20Identity = MscorlibRef_v20.GetAssemblyIdentity(); var systemRefIdentity = SystemRef.GetAssemblyIdentity(); var systemRef20Identity = SystemRef_v20.GetAssemblyIdentity(); // No duplicates. VerifyAssemblyReferences( referenceBN1, ImmutableArray.Create(MscorlibRef, referenceAS1, referenceBN1), ImmutableArray.Create(mscorlibIdentity, identityAS1, identityBN1)); // No duplicates, extra references. VerifyAssemblyReferences( referenceAS1, ImmutableArray.Create(MscorlibRef, referenceBN1, referenceAS1, referenceBS2), ImmutableArray.Create(mscorlibIdentity, identityAS1)); // Strong-named, non-strong-named, and framework duplicates, same version (no aliases). VerifyAssemblyReferences( referenceBN2, ImmutableArray.Create(MscorlibRef, referenceAS1, MscorlibRef, referenceBN2, referenceBN2, referenceAS1, referenceAS1), ImmutableArray.Create(mscorlibIdentity, identityAS1, identityBN2)); // Strong-named, non-strong-named, and framework duplicates, different versions. VerifyAssemblyReferences( referenceBN1, ImmutableArray.Create(MscorlibRef, referenceAS1, MscorlibRef_v20, referenceAS2, referenceBN2, referenceBN1, referenceAS2, referenceAS1, referenceBN1), ImmutableArray.Create(mscorlibIdentity, identityAS2, identityBN2)); VerifyAssemblyReferences( referenceBN2, ImmutableArray.Create(MscorlibRef, referenceAS1, MscorlibRef_v20, referenceAS2, referenceBN2, referenceBN1, referenceAS2, referenceAS1, referenceBN1), ImmutableArray.Create(mscorlibIdentity, identityAS2, identityBN2)); // Strong-named, different versions. VerifyAssemblyReferences( referenceBS1, ImmutableArray.Create(MscorlibRef, referenceAS1, referenceAS2, referenceBS2, referenceBS1, referenceAS2, referenceAS1, referenceBS1), ImmutableArray.Create(mscorlibIdentity, identityAS2, identityBS2)); VerifyAssemblyReferences( referenceBS2, ImmutableArray.Create(MscorlibRef, referenceAS1, referenceAS2, referenceBS2, referenceBS1, referenceAS2, referenceAS1, referenceBS1), ImmutableArray.Create(mscorlibIdentity, identityAS2, identityBS2)); // Assembly C, multiple versions, not strong name. var compilationCN1 = CreateCompilation( new AssemblyIdentity("C", new Version(1, 1, 1, 1)), new[] { sourceC }, references: new[] { MscorlibRef, referenceBS1 }, options: TestOptions.DebugDll); // Duplicate assemblies, target module referencing BS1. WithRuntimeInstance(compilationCN1, new[] { MscorlibRef, referenceAS1, referenceAS2, referenceBS2, referenceBS1, referenceBS2 }, runtime => { ImmutableArray<MetadataBlock> typeBlocks; ImmutableArray<MetadataBlock> methodBlocks; Guid moduleVersionId; ISymUnmanagedReader symReader; int typeToken; int methodToken; int localSignatureToken; GetContextState(runtime, "C", out typeBlocks, out moduleVersionId, out symReader, out typeToken, out localSignatureToken); GetContextState(runtime, "C.M", out methodBlocks, out moduleVersionId, out symReader, out methodToken, out localSignatureToken); uint ilOffset = ExpressionCompilerTestHelpers.GetOffset(methodToken, symReader); // Compile expression with type context with all modules. var appDomain = new AppDomain(); var context = CreateTypeContext( appDomain, typeBlocks, moduleVersionId, typeToken, MakeAssemblyReferencesKind.AllAssemblies); Assert.Equal(identityAS2, context.Compilation.GlobalNamespace.GetMembers("A").OfType<NamedTypeSymbol>().Single().ContainingAssembly.Identity); Assert.Equal(identityBS2, context.Compilation.GlobalNamespace.GetMembers("B").OfType<NamedTypeSymbol>().Single().ContainingAssembly.Identity); string error; // A could be ambiguous, but the ambiguity is resolved in favor of the newer assembly. var testData = new CompilationTestData(); context.CompileExpression("new A()", out error, testData); Assert.Null(error); // B could be ambiguous, but the ambiguity is resolved in favor of the newer assembly. testData = new CompilationTestData(); context.CompileExpression("new B()", out error, testData); Assert.Null(error); appDomain.SetMetadataContext( SetMetadataContext( new MetadataContext<CSharpMetadataContext>(typeBlocks, ImmutableDictionary<MetadataContextId, CSharpMetadataContext>.Empty), default(Guid), new CSharpMetadataContext(context.Compilation))); // Compile expression with type context with referenced modules only. context = CreateTypeContext( appDomain, typeBlocks, moduleVersionId, typeToken, MakeAssemblyReferencesKind.DirectReferencesOnly); // A is unrecognized since there were no direct references to AS1 or AS2. testData = new CompilationTestData(); context.CompileExpression("new A()", out error, testData); Assert.Equal("error CS0246: The type or namespace name 'A' could not be found (are you missing a using directive or an assembly reference?)", error); testData = new CompilationTestData(); // B should be resolved to BS2. context.CompileExpression("new B()", out error, testData); var methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""B..ctor()"" IL_0005: ret }"); Assert.Equal(((MethodSymbol)methodData.Method).ReturnType.ContainingAssembly.ToDisplayString(), identityBS2.GetDisplayName()); // B.F should result in missing assembly AS2 since there were no direct references to AS2. ResultProperties resultProperties; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; testData = new CompilationTestData(); context.CompileExpression( "(new B()).F", DkmEvaluationFlags.None, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); AssertEx.Equal(missingAssemblyIdentities, ImmutableArray.Create(identityAS2)); // Compile expression with method context with all modules. var previous = appDomain.GetMetadataContext(); context = CreateMethodContext( appDomain, methodBlocks, symReader, moduleVersionId, methodToken: methodToken, methodVersion: 1, ilOffset: ilOffset, localSignatureToken: localSignatureToken, MakeAssemblyReferencesKind.AllAssemblies); Assert.NotSame(GetMetadataContext(previous).EvaluationContext, context); Assert.Same(GetMetadataContext(previous).Compilation, context.Compilation); // re-use type context compilation testData = new CompilationTestData(); // A could be ambiguous, but the ambiguity is resolved in favor of the newer assembly. testData = new CompilationTestData(); context.CompileExpression("new A()", out error, testData); Assert.Null(error); // B could be ambiguous, but the ambiguity is resolved in favor of the newer assembly. testData = new CompilationTestData(); context.CompileExpression("new B()", out error, testData); Assert.Null(error); // Compile expression with method context with referenced modules only. context = CreateMethodContext( appDomain, methodBlocks, symReader, moduleVersionId, methodToken: methodToken, methodVersion: 1, ilOffset: ilOffset, localSignatureToken: localSignatureToken, MakeAssemblyReferencesKind.DirectReferencesOnly); // A is unrecognized since there were no direct references to AS1 or AS2. testData = new CompilationTestData(); context.CompileExpression("new A()", out error, testData); Assert.Equal("error CS0246: The type or namespace name 'A' could not be found (are you missing a using directive or an assembly reference?)", error); testData = new CompilationTestData(); // B should be resolved to BS2. context.CompileExpression("new B()", out error, testData); methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""B..ctor()"" IL_0005: ret }"); Assert.Equal(((MethodSymbol)methodData.Method).ReturnType.ContainingAssembly.ToDisplayString(), identityBS2.GetDisplayName()); // B.F should result in missing assembly AS2 since there were no direct references to AS2. testData = new CompilationTestData(); context.CompileExpression( "(new B()).F", DkmEvaluationFlags.None, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); AssertEx.Equal(missingAssemblyIdentities, ImmutableArray.Create(identityAS2)); }); } private static (AssemblyIdentity Identity, ModuleInstance Module, MetadataReference Reference) Compile(string assemblyName, string source, params MetadataReference[] references) { var compilation = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, references: references, assemblyName: assemblyName); compilation.VerifyDiagnostics(); var module = compilation.ToModuleInstance(); return (compilation.Assembly.Identity, module, module.GetReference()); } private static (AssemblyIdentity Identity, ModuleInstance Module, MetadataReference Reference) Compile(AssemblyIdentity identity, string source, CSharpCompilationOptions options, params MetadataReference[] references) { var compilation = CreateCompilation(identity, new[] { source }, references: references, options: options); compilation.VerifyDiagnostics(); var module = compilation.ToModuleInstance(); return (compilation.Assembly.Identity, module, module.GetReference()); } private static void VerifyAssemblyReferences( MetadataReference target, ImmutableArray<MetadataReference> references, ImmutableArray<AssemblyIdentity> expectedIdentities) { Assert.True(references.Contains(target)); var modules = references.SelectAsArray(r => r.ToModuleInstance()); using (var runtime = new RuntimeInstance(modules, DebugInformationFormat.Pdb)) { var moduleVersionId = target.GetModuleVersionId(); var blocks = runtime.Modules.SelectAsArray(m => m.MetadataBlock); IReadOnlyDictionary<string, ImmutableArray<(AssemblyIdentity, MetadataReference)>> referencesBySimpleName; var actualReferences = blocks.MakeAssemblyReferences(moduleVersionId, CompilationExtensions.IdentityComparer, MakeAssemblyReferencesKind.DirectReferencesOnly, out referencesBySimpleName); Assert.Null(referencesBySimpleName); // Verify identities. var actualIdentities = actualReferences.SelectAsArray(r => r.GetAssemblyIdentity()); AssertEx.Equal(expectedIdentities, actualIdentities); // Verify identities are unique. var uniqueIdentities = actualIdentities.Distinct(); Assert.Equal(actualIdentities.Length, uniqueIdentities.Length); actualReferences = blocks.MakeAssemblyReferences(moduleVersionId, CompilationExtensions.IdentityComparer, MakeAssemblyReferencesKind.AllReferences, out referencesBySimpleName); Assert.Equal(2, actualReferences.Length); Assert.Equal(moduleVersionId, actualReferences[1].GetModuleVersionId()); foreach (var reference in references) { var identity = reference.GetAssemblyIdentity(); var pairs = referencesBySimpleName[identity.Name]; var other = pairs.FirstOrDefault(p => identity.Equals(p.Item1)); Assert.Equal(identity, other.Item1); } } } private static void VerifyResolutionRequests(EvaluationContext context, params (AssemblyIdentity, AssemblyIdentity, int)[] expectedRequests) { ExpressionCompilerTestHelpers.VerifyResolutionRequests( (EEMetadataReferenceResolver)context.Compilation.Options.MetadataReferenceResolver, expectedRequests); } [Fact] public void DuplicateTypesAndMethodsDifferentAssemblies() { var sourceA = @"using N; namespace N { class C1 { } public static class E { public static A F(this A o) { return o; } } } class C2 { } public class A { public static void M() { var x = new A(); var y = x.F(); } }"; var sourceB = @"using N; namespace N { class C1 { } public static class E { public static int F(this A o) { return 2; } } } class C2 { } public class B { static void M() { var x = new A(); } }"; var compilationA = CreateCompilationWithMscorlib40AndSystemCore(sourceA, options: TestOptions.DebugDll); var identityA = compilationA.Assembly.Identity; var moduleA = compilationA.ToModuleInstance(); var compilationB = CreateCompilationWithMscorlib40AndSystemCore(sourceB, options: TestOptions.DebugDll, references: new[] { moduleA.GetReference() }); var moduleB = compilationB.ToModuleInstance(); var runtime = CreateRuntimeInstance(new[] { MscorlibRef.ToModuleInstance(), SystemCoreRef.ToModuleInstance(), moduleA, moduleB }); ImmutableArray<MetadataBlock> blocks; Guid moduleVersionId; ISymUnmanagedReader symReader; int typeToken; int methodToken; int localSignatureToken; GetContextState(runtime, "B", out blocks, out moduleVersionId, out symReader, out typeToken, out localSignatureToken); string errorMessage; CompilationTestData testData; var contextFactory = CreateTypeContextFactory(moduleVersionId, typeToken); // Duplicate type in namespace, at type scope. ExpressionCompilerTestHelpers.CompileExpressionWithRetry(blocks, "new N.C1()", ImmutableArray<Alias>.Empty, contextFactory, getMetaDataBytesPtr: null, errorMessage: out errorMessage, testData: out testData); IEnumerable<string> CS0433Messages(string type) { yield return "error CS0433: " + string.Format(CSharpResources.ERR_SameFullNameAggAgg, compilationA.Assembly.Identity, type, compilationB.Assembly.Identity); yield return "error CS0433: " + string.Format(CSharpResources.ERR_SameFullNameAggAgg, compilationB.Assembly.Identity, type, compilationA.Assembly.Identity); } Assert.Contains(errorMessage, CS0433Messages("C1")); GetContextState(runtime, "B.M", out blocks, out moduleVersionId, out symReader, out methodToken, out localSignatureToken); contextFactory = CreateMethodContextFactory(moduleVersionId, symReader, methodToken, localSignatureToken); // Duplicate type in namespace, at method scope. ExpressionCompilerTestHelpers.CompileExpressionWithRetry(blocks, "new C1()", ImmutableArray<Alias>.Empty, contextFactory, getMetaDataBytesPtr: null, errorMessage: out errorMessage, testData: out testData); Assert.Contains(errorMessage, CS0433Messages("C1")); // Duplicate type in global namespace, at method scope. ExpressionCompilerTestHelpers.CompileExpressionWithRetry(blocks, "new C2()", ImmutableArray<Alias>.Empty, contextFactory, getMetaDataBytesPtr: null, errorMessage: out errorMessage, testData: out testData); Assert.Contains(errorMessage, CS0433Messages("C2")); // Duplicate extension method, at method scope. ExpressionCompilerTestHelpers.CompileExpressionWithRetry(blocks, "x.F()", ImmutableArray<Alias>.Empty, contextFactory, getMetaDataBytesPtr: null, errorMessage: out errorMessage, testData: out testData); Assert.Equal($"error CS0121: { string.Format(CSharpResources.ERR_AmbigCall, "N.E.F(A)", "N.E.F(A)") }", errorMessage); // Same tests as above but in library that does not directly reference duplicates. GetContextState(runtime, "A", out blocks, out moduleVersionId, out symReader, out typeToken, out localSignatureToken); contextFactory = CreateTypeContextFactory(moduleVersionId, typeToken); // Duplicate type in namespace, at type scope. ExpressionCompilerTestHelpers.CompileExpressionWithRetry(blocks, "new N.C1()", ImmutableArray<Alias>.Empty, contextFactory, getMetaDataBytesPtr: null, errorMessage: out errorMessage, testData: out testData); Assert.Null(errorMessage); var methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""N.C1..ctor()"" IL_0005: ret }"); Assert.Equal(((MethodSymbol)methodData.Method).ReturnType.ContainingAssembly.ToDisplayString(), identityA.GetDisplayName()); GetContextState(runtime, "A.M", out blocks, out moduleVersionId, out symReader, out methodToken, out localSignatureToken); contextFactory = CreateMethodContextFactory(moduleVersionId, symReader, methodToken, localSignatureToken); // Duplicate type in global namespace, at method scope. ExpressionCompilerTestHelpers.CompileExpressionWithRetry(blocks, "new C2()", ImmutableArray<Alias>.Empty, contextFactory, getMetaDataBytesPtr: null, errorMessage: out errorMessage, testData: out testData); Assert.Null(errorMessage); methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 6 (0x6) .maxstack 1 .locals init (A V_0, //x A V_1) //y IL_0000: newobj ""C2..ctor()"" IL_0005: ret }"); Assert.Equal(((MethodSymbol)methodData.Method).ReturnType.ContainingAssembly.ToDisplayString(), identityA.GetDisplayName()); // Duplicate extension method, at method scope. ExpressionCompilerTestHelpers.CompileExpressionWithRetry(blocks, "x.F()", ImmutableArray<Alias>.Empty, contextFactory, getMetaDataBytesPtr: null, errorMessage: out errorMessage, testData: out testData); Assert.Null(errorMessage); methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 7 (0x7) .maxstack 1 .locals init (A V_0, //x A V_1) //y IL_0000: ldloc.0 IL_0001: call ""A N.E.F(A)"" IL_0006: ret }"); Assert.Equal(((MethodSymbol)methodData.Method).ReturnType.ContainingAssembly.ToDisplayString(), identityA.GetDisplayName()); } /// <summary> /// mscorlib.dll is not directly referenced from an assembly /// compiled against portable framework assemblies. /// </summary> [WorkItem(1150981, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1150981")] [Fact] public void MissingMscorlib() { var sourceA = @"public class A { } class B { } class C { }"; var sourceB = @"public class B : A { }"; var moduleA = CreateEmptyCompilation( sourceA, references: new[] { SystemRuntimePP7Ref }, options: TestOptions.DebugDll).ToModuleInstance(); var moduleB = CreateEmptyCompilation( sourceB, references: new[] { SystemRuntimePP7Ref, moduleA.GetReference() }, options: TestOptions.DebugDll).ToModuleInstance(); // Include an empty assembly to verify that not all assemblies // with no references are treated as mscorlib. var referenceC = AssemblyMetadata.CreateFromImage(TestResources.ExpressionCompiler.Empty).GetReference(); // At runtime System.Runtime.dll contract assembly is replaced // by mscorlib.dll and System.Runtime.dll facade assemblies. var runtime = CreateRuntimeInstance(new[] { MscorlibFacadeRef.ToModuleInstance(), SystemRuntimeFacadeRef.ToModuleInstance(), moduleA, moduleB, referenceC.ToModuleInstance() }); ImmutableArray<MetadataBlock> blocks; Guid moduleVersionId; ISymUnmanagedReader symReader; int typeToken; int localSignatureToken; GetContextState(runtime, "C", out blocks, out moduleVersionId, out symReader, out typeToken, out localSignatureToken); string errorMessage; CompilationTestData testData; int attempts = 0; EvaluationContextBase contextFactory(ImmutableArray<MetadataBlock> b, bool u) { attempts++; return EvaluationContext.CreateTypeContext( ToCompilation(b, u, moduleVersionId), moduleVersionId, typeToken); } // Compile: [DebuggerDisplay("{new B()}")] const string expr = "new B()"; ExpressionCompilerTestHelpers.CompileExpressionWithRetry(blocks, expr, ImmutableArray<Alias>.Empty, contextFactory, getMetaDataBytesPtr: null, errorMessage: out errorMessage, testData: out testData); Assert.Null(errorMessage); Assert.Equal(2, attempts); var methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""B..ctor()"" IL_0005: ret }"); } [WorkItem(1170032, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1170032")] [Fact] public void DuplicateTypesInMscorlib() { var sourceConsole = @"namespace System { public class Console { } }"; var sourceObjectModel = @"namespace System.Collections.ObjectModel { public class ReadOnlyDictionary<K, V> { } }"; var source = @"class C { static void Main() { var t = typeof(System.Console); var o = (System.Collections.ObjectModel.ReadOnlyDictionary<object, object>)null; } }"; var systemConsoleComp = CreateCompilation(sourceConsole, options: TestOptions.DebugDll, assemblyName: "System.Console"); var systemConsoleRef = systemConsoleComp.EmitToImageReference(); var systemObjectModelComp = CreateCompilation(sourceObjectModel, options: TestOptions.DebugDll, assemblyName: "System.ObjectModel"); var systemObjectModelRef = systemObjectModelComp.EmitToImageReference(); var identityObjectModel = systemObjectModelRef.GetAssemblyIdentity(); // At runtime System.Runtime.dll contract assembly is replaced // by mscorlib.dll and System.Runtime.dll facade assemblies; // System.Console.dll and System.ObjectModel.dll are not replaced. // Test different ordering of modules containing duplicates: // { System.Console, mscorlib } and { mscorlib, System.ObjectModel }. var contractReferences = ImmutableArray.Create(systemConsoleRef, SystemRuntimePP7Ref, systemObjectModelRef); var runtimeReferences = ImmutableArray.Create(systemConsoleRef, MscorlibFacadeRef, SystemRuntimeFacadeRef, systemObjectModelRef); // Verify the compiler reports duplicate types with facade assemblies. var compilation = CreateEmptyCompilation( source, references: runtimeReferences, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName()); compilation.VerifyDiagnostics( // error CS0433: The type 'Console' exists in both 'System.Console, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' // var t = typeof(System.Console); Diagnostic(ErrorCode.ERR_SameFullNameAggAgg, "Console").WithArguments("System.Console, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "System.Console", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089").WithLocation(5, 31), // error CS0433: The type 'ReadOnlyDictionary<K, V>' exists in both 'System.ObjectModel, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' // var o = (System.Collections.ObjectModel.ReadOnlyDictionary<object, object>)null; Diagnostic(ErrorCode.ERR_SameFullNameAggAgg, "ReadOnlyDictionary<object, object>").WithArguments("System.ObjectModel, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "System.Collections.ObjectModel.ReadOnlyDictionary<K, V>", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089").WithLocation(6, 49)); // EE should not report duplicate type when the original source // is compiled with contract assemblies and the EE expression // is compiled with facade assemblies. compilation = CreateEmptyCompilation( source, references: contractReferences, options: TestOptions.DebugDll); WithRuntimeInstance(compilation, runtimeReferences, runtime => { var context = CreateMethodContext(runtime, "C.Main"); string errorMessage; // { System.Console, mscorlib } var testData = new CompilationTestData(); context.CompileExpression("typeof(System.Console)", out errorMessage, testData); var methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL(@" { // Code size 11 (0xb) .maxstack 1 .locals init (System.Type V_0, //t System.Collections.ObjectModel.ReadOnlyDictionary<object, object> V_1) //o IL_0000: ldtoken ""System.Console"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ret }"); // { mscorlib, System.ObjectModel } testData = new CompilationTestData(); context.CompileExpression("(System.Collections.ObjectModel.ReadOnlyDictionary<object, object>)null", out errorMessage, testData); methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL(@" { // Code size 2 (0x2) .maxstack 1 .locals init (System.Type V_0, //t System.Collections.ObjectModel.ReadOnlyDictionary<object, object> V_1) //o IL_0000: ldnull IL_0001: ret }"); Assert.Equal(((MethodSymbol)methodData.Method).ReturnType.ContainingAssembly.ToDisplayString(), identityObjectModel.GetDisplayName()); }); } /// <summary> /// Intrinsic methods assembly should not be dropped. /// </summary> [WorkItem(4140, "https://github.com/dotnet/roslyn/issues/4140")] [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] public void IntrinsicMethods() { var sourceA = @"public class A { }"; var sourceB = @"public class A { } public class B { static void M(A a) { } }"; var compilationA = CreateCompilationWithMscorlib40AndSystemCore(sourceA, options: TestOptions.DebugDll); var moduleA = compilationA.ToModuleInstance(); var compilationB = CreateCompilationWithMscorlib40AndSystemCore(sourceB, options: TestOptions.DebugDll, references: new[] { moduleA.GetReference() }); var moduleB = compilationB.ToModuleInstance(); var runtime = CreateRuntimeInstance(new[] { MscorlibRef.ToModuleInstance(), SystemCoreRef.ToModuleInstance(), moduleA, moduleB, ExpressionCompilerTestHelpers.IntrinsicAssemblyReference.ToModuleInstance() }); ImmutableArray<MetadataBlock> blocks; Guid moduleVersionId; ISymUnmanagedReader symReader; int methodToken; int localSignatureToken; GetContextState(runtime, "B.M", out blocks, out moduleVersionId, out symReader, out methodToken, out localSignatureToken); var aliases = ImmutableArray.Create( ExceptionAlias(typeof(ArgumentException)), ReturnValueAlias(2, typeof(string)), ObjectIdAlias(1, typeof(object))); int attempts = 0; EvaluationContextBase contextFactory(ImmutableArray<MetadataBlock> b, bool u) { attempts++; return EvaluationContext.CreateMethodContext( ToCompilation(b, u, moduleVersionId), symReader, moduleVersionId, methodToken, methodVersion: 1, ilOffset: 0, localSignatureToken: localSignatureToken); } string errorMessage; CompilationTestData testData; ExpressionCompilerTestHelpers.CompileExpressionWithRetry( blocks, "(object)new A() ?? $exception ?? $1 ?? $ReturnValue2", aliases, contextFactory, getMetaDataBytesPtr: null, errorMessage: out errorMessage, testData: out testData); Assert.Null(errorMessage); Assert.Equal(2, attempts); var methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 49 (0x31) .maxstack 2 IL_0000: newobj ""A..ctor()"" IL_0005: dup IL_0006: brtrue.s IL_0030 IL_0008: pop IL_0009: call ""System.Exception Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetException()"" IL_000e: castclass ""System.ArgumentException"" IL_0013: dup IL_0014: brtrue.s IL_0030 IL_0016: pop IL_0017: ldstr ""$1"" IL_001c: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_0021: dup IL_0022: brtrue.s IL_0030 IL_0024: pop IL_0025: ldc.i4.2 IL_0026: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetReturnValue(int)"" IL_002b: castclass ""string"" IL_0030: ret }"); } private const string CorLibAssemblyName = "System.Private.CoreLib"; // An assembly with the expected corlib name and with System.Object should // be considered the corlib, even with references to external assemblies. [WorkItem(13275, "https://github.com/dotnet/roslyn/issues/13275")] [WorkItem(30030, "https://github.com/dotnet/roslyn/issues/30030")] [Fact] public void CorLibWithAssemblyReferences() { string sourceLib = @"public class Private1 { } public class Private2 { }"; var compLib = CreateCompilation(sourceLib, assemblyName: "System.Private.Library"); compLib.VerifyDiagnostics(); var refLib = compLib.EmitToImageReference(); string sourceCorLib = @"using System.Runtime.CompilerServices; [assembly: TypeForwardedTo(typeof(Private2))] namespace System { public class Object { public Private1 F() => null; } #pragma warning disable 0436 public class Void : Object { } #pragma warning restore 0436 }"; // Create a custom corlib with a reference to compilation // above and a reference to the actual mscorlib. var compCorLib = CreateEmptyCompilation(sourceCorLib, assemblyName: CorLibAssemblyName, references: new[] { MscorlibRef, refLib }); compCorLib.VerifyDiagnostics(); var objectType = compCorLib.SourceAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("System.Object"); Assert.NotNull(objectType.BaseType()); ImmutableArray<byte> peBytes; ImmutableArray<byte> pdbBytes; ExpressionCompilerTestHelpers.EmitCorLibWithAssemblyReferences( compCorLib, null, (moduleBuilder, emitOptions) => new PEAssemblyBuilderWithAdditionalReferences(moduleBuilder, emitOptions, objectType.GetCciAdapter()), out peBytes, out pdbBytes); using (var reader = new PEReader(peBytes)) { var metadata = reader.GetMetadata(); var module = metadata.ToModuleMetadata(ignoreAssemblyRefs: true); var metadataReader = metadata.ToMetadataReader(); var moduleInstance = ModuleInstance.Create(metadata, metadataReader.GetModuleVersionIdOrThrow()); // Verify the module declares System.Object. Assert.True(metadataReader.DeclaresTheObjectClass()); // Verify the PEModule has no assembly references. Assert.Equal(0, module.Module.ReferencedAssemblies.Length); // Verify the underlying metadata has the expected assembly references. var actualReferences = metadataReader.AssemblyReferences.Select(r => metadataReader.GetString(metadataReader.GetAssemblyReference(r).Name)).ToImmutableArray(); AssertEx.Equal(new[] { "mscorlib", "System.Private.Library" }, actualReferences); var source = @"class C { static void M() { } }"; var comp = CreateEmptyCompilation(source, options: TestOptions.DebugDll, references: new[] { refLib, AssemblyMetadata.Create(module).GetReference() }); comp.VerifyDiagnostics(); using (var runtime = RuntimeInstance.Create(new[] { comp.ToModuleInstance(), moduleInstance })) { string error; var context = CreateMethodContext(runtime, "C.M"); // Valid expression. var testData = new CompilationTestData(); context.CompileExpression( "new object()", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 6 (0x6) .maxstack 1 IL_0000: newobj ""object..ctor()"" IL_0005: ret }"); // Invalid expression: System.Int32 is not defined in corlib above. testData = new CompilationTestData(); context.CompileExpression( "1", out error, testData); Assert.Equal("error CS0518: Predefined type 'System.Int32' is not defined or imported", error); // Invalid expression: type in method signature from missing referenced assembly. testData = new CompilationTestData(); context.CompileExpression( "(new object()).F()", out error, testData); Assert.Equal("error CS0570: 'object.F()' is not supported by the language", error); // Invalid expression: type forwarded to missing referenced assembly. testData = new CompilationTestData(); context.CompileExpression( "new Private2()", out error, testData); Assert.Equal("error CS0246: The type or namespace name 'Private2' could not be found (are you missing a using directive or an assembly reference?)", error); } } } // References to missing assembly from PDB custom debug info. [WorkItem(13275, "https://github.com/dotnet/roslyn/issues/13275")] [Theory] [MemberData(nameof(NonNullTypesTrueAndFalseReleaseDll))] public void CorLibWithAssemblyReferences_Pdb(CSharpCompilationOptions options) { string sourceLib = @"namespace Namespace { public class Private { } }"; var compLib = CreateCompilation(sourceLib, assemblyName: "System.Private.Library"); compLib.VerifyDiagnostics(); var refLib = compLib.EmitToImageReference(aliases: ImmutableArray.Create("A")); string sourceCorLib = @"extern alias A; #pragma warning disable 8019 using N = A::Namespace; namespace System { public class Object { public void F() { } } #pragma warning disable 0436 public class Void : Object { } #pragma warning restore 0436 }"; // Create a custom corlib with a reference to compilation // above and a reference to the actual mscorlib. var compCorLib = CreateEmptyCompilation(sourceCorLib, assemblyName: CorLibAssemblyName, references: new[] { MscorlibRef, refLib }, options: options); compCorLib.VerifyDiagnostics(); var objectType = compCorLib.SourceAssembly.GlobalNamespace.GetMember<NamedTypeSymbol>("System.Object"); Assert.NotNull(objectType.BaseType()); var pdbPath = Temp.CreateDirectory().Path; ImmutableArray<byte> peBytes; ImmutableArray<byte> pdbBytes; ExpressionCompilerTestHelpers.EmitCorLibWithAssemblyReferences( compCorLib, pdbPath, (moduleBuilder, emitOptions) => new PEAssemblyBuilderWithAdditionalReferences(moduleBuilder, emitOptions, objectType.GetCciAdapter()), out peBytes, out pdbBytes); var symReader = SymReaderFactory.CreateReader(pdbBytes); using (var reader = new PEReader(peBytes)) { var metadata = reader.GetMetadata(); var module = metadata.ToModuleMetadata(ignoreAssemblyRefs: true); var metadataReader = metadata.ToMetadataReader(); var moduleInstance = ModuleInstance.Create(metadata, metadataReader.GetModuleVersionIdOrThrow(), symReader); // Verify the module declares System.Object. Assert.True(metadataReader.DeclaresTheObjectClass()); // Verify the PEModule has no assembly references. Assert.Equal(0, module.Module.ReferencedAssemblies.Length); // Verify the underlying metadata has the expected assembly references. var actualReferences = metadataReader.AssemblyReferences.Select(r => metadataReader.GetString(metadataReader.GetAssemblyReference(r).Name)).ToImmutableArray(); AssertEx.Equal(new[] { "mscorlib", "System.Private.Library" }, actualReferences); using (var runtime = RuntimeInstance.Create(new[] { moduleInstance })) { string error; var context = CreateMethodContext(runtime, "System.Object.F"); var testData = new CompilationTestData(); // Invalid import: "using N = A::Namespace;". context.CompileExpression( "new N.Private()", out error, testData); Assert.Equal("error CS0246: The type or namespace name 'N' could not be found (are you missing a using directive or an assembly reference?)", error); } } } // An assembly with the expected corlib name but without // System.Object should not be considered the corlib. [Fact] public void CorLibWithAssemblyReferencesNoSystemObject() { // Assembly with expected corlib name but without System.Object declared. string sourceLib = @"class Private { }"; var compLib = CreateCompilation(sourceLib, assemblyName: CorLibAssemblyName); compLib.VerifyDiagnostics(); var refLib = compLib.EmitToImageReference(); var source = @"class C { static void M() { } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics(); using (var runtime = RuntimeInstance.Create(new[] { comp.ToModuleInstance(), refLib.ToModuleInstance(), MscorlibRef.ToModuleInstance() })) { string error; var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); context.CompileExpression( "1.GetType()", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 12 (0xc) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: call ""System.Type object.GetType()"" IL_000b: ret }"); } } private static ExpressionCompiler.CreateContextDelegate CreateTypeContextFactory( Guid moduleVersionId, int typeToken) { return (blocks, useReferencedModulesOnly) => EvaluationContext.CreateTypeContext( ToCompilation(blocks, useReferencedModulesOnly, moduleVersionId), moduleVersionId, typeToken); } private static ExpressionCompiler.CreateContextDelegate CreateMethodContextFactory( Guid moduleVersionId, ISymUnmanagedReader symReader, int methodToken, int localSignatureToken) { return (blocks, useReferencedModulesOnly) => EvaluationContext.CreateMethodContext( ToCompilation(blocks, useReferencedModulesOnly, moduleVersionId), symReader, moduleVersionId, methodToken, methodVersion: 1, ilOffset: 0, localSignatureToken: localSignatureToken); } private static CSharpCompilation ToCompilation( ImmutableArray<MetadataBlock> blocks, bool useReferencedModulesOnly, Guid moduleVersionId) { return blocks.ToCompilation(moduleVersionId, useReferencedModulesOnly ? MakeAssemblyReferencesKind.DirectReferencesOnly : MakeAssemblyReferencesKind.AllAssemblies); } private sealed class PEAssemblyBuilderWithAdditionalReferences : PEModuleBuilder, IAssemblyReference { private readonly CommonPEModuleBuilder _builder; private readonly NamespaceTypeDefinitionNoBase _objectType; internal PEAssemblyBuilderWithAdditionalReferences(CommonPEModuleBuilder builder, EmitOptions emitOptions, INamespaceTypeDefinition objectType) : base((SourceModuleSymbol)builder.CommonSourceModule, emitOptions, builder.OutputKind, builder.SerializationProperties, builder.ManifestResources) { _builder = builder; _objectType = new NamespaceTypeDefinitionNoBase(objectType); } public override IEnumerable<INamespaceTypeDefinition> GetTopLevelSourceTypeDefinitions(EmitContext context) { foreach (var type in base.GetTopLevelSourceTypeDefinitions(context)) { yield return (type == _objectType.UnderlyingType) ? _objectType : type; } } public override SymbolChanges EncSymbolChanges => _builder.EncSymbolChanges; public override EmitBaseline PreviousGeneration => _builder.PreviousGeneration; public override ISourceAssemblySymbolInternal SourceAssemblyOpt => _builder.SourceAssemblyOpt; public override IEnumerable<IFileReference> GetFiles(EmitContext context) => _builder.GetFiles(context); protected override void AddEmbeddedResourcesFromAddedModules(ArrayBuilder<ManagedResource> builder, DiagnosticBag diagnostics) { } internal override SynthesizedAttributeData SynthesizeEmbeddedAttribute() { throw new NotImplementedException(); } AssemblyIdentity IAssemblyReference.Identity => ((IAssemblyReference)_builder).Identity; Version IAssemblyReference.AssemblyVersionPattern => ((IAssemblyReference)_builder).AssemblyVersionPattern; } } }
-1
dotnet/roslyn
55,409
Use FixedSize API
tmat
2021-08-04T19:30:40Z
2021-08-04T21:53:46Z
e0112742bff208dd0546de45e36f7b52058a45a3
c90bf0ec986010051662c8e1fbc872c2fd86bc4e
Use FixedSize API.
./src/Compilers/CSharp/Test/Semantic/Semantics/ForEachTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { /// <summary> /// Tests related to binding (but not lowering) foreach loops. /// </summary> public class ForEachTests : CompilingTestBase { [Fact] public void TestErrorBadElementType() { // See bug 7419. var text = @" class C { static void Main() { System.Collections.IEnumerable sequence = null; foreach (MissingType x in sequence) { bool b = !x.Equals(null); } } }"; CreateCompilation(text).VerifyDiagnostics( // (7,18): error CS0246: The type or namespace name 'MissingType' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "MissingType").WithArguments("MissingType")); } [Fact] public void TestErrorNullLiteralCollection() { var text = @" class C { static void Main() { foreach (int x in null) { } } }"; CreateCompilation(text).VerifyDiagnostics( // (6,27): error CS0186: Use of null is not valid in this context Diagnostic(ErrorCode.ERR_NullNotValid, "null")); } [Fact] public void TestErrorNullConstantCollection() { var text = @" class C { static void Main() { const object NULL = null; foreach (int x in NULL) { } } }"; CreateCompilation(text).VerifyDiagnostics( // (7,27): error CS1579: foreach statement cannot operate on variables of type 'object' because 'object' does not contain a public instance or extension definition for 'GetEnumerator' // foreach (int x in NULL) Diagnostic(ErrorCode.ERR_ForEachMissingMember, "NULL").WithArguments("object", "GetEnumerator").WithLocation(7, 27) ); } [WorkItem(540957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540957")] [Fact] public void TestErrorDefaultOfArrayType() { var text = @" class C { static void Main() { foreach (int x in default(int[])) { } } }"; CreateCompilation(text).VerifyDiagnostics( // (7,27): error CS0186: Use of null is not valid in this context Diagnostic(ErrorCode.ERR_NullNotValid, "default(int[])")); } [Fact] public void TestErrorLambdaCollection() { var text = @" class C { static void Main() { foreach (int x in (() => {})) { } } }"; CreateCompilation(text).VerifyDiagnostics( // (6,27): error CS0446: Foreach cannot operate on a 'lambda expression'. Did you intend to invoke the 'lambda expression'? Diagnostic(ErrorCode.ERR_AnonMethGrpInForEach, "(() => {})").WithArguments("lambda expression")); } [Fact] public void TestErrorMethodGroupCollection() { var text = @" class C { static void Main() { foreach (int x in Main) { } } }"; CreateCompilation(text).VerifyDiagnostics( // (6,27): error CS0446: Foreach cannot operate on a 'method group'. Did you intend to invoke the 'method group'? Diagnostic(ErrorCode.ERR_AnonMethGrpInForEach, "Main").WithArguments("method group")); } [Fact] public void TestErrorNoElementConversion() { var text = @" class C { static void Main(string[] args) { foreach (int x in args) { } } }"; CreateCompilation(text).VerifyDiagnostics( // (6,9): error CS0030: Cannot convert type 'string' to 'int' Diagnostic(ErrorCode.ERR_NoExplicitConv, "foreach").WithArguments("string", "int")); } [Fact] public void TestErrorPatternNoGetEnumerator() { var text = @" class C { static void Main(string[] args) { foreach (int x in new Enumerable()) { } } } class Enumerable { //public Enumerator GetEnumerator() { return new Enumerator(); } } class Enumerator { public int Current { get { return 1; } } public bool MoveNext() { return false; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,27): error CS1579: foreach statement cannot operate on variables of type 'Enumerable' because 'Enumerable' does not contain a public definition for 'GetEnumerator' Diagnostic(ErrorCode.ERR_ForEachMissingMember, "new Enumerable()").WithArguments("Enumerable", "GetEnumerator")); } [Fact] public void TestErrorPatternInaccessibleGetEnumerator() { var text = @" class C { static void Main(string[] args) { foreach (int x in new Enumerable()) { } } } class Enumerable { private Enumerator GetEnumerator() { return new Enumerator(); } } class Enumerator { public int Current { get { return 1; } } public bool MoveNext() { return false; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,27): error CS1579: foreach statement cannot operate on variables of type 'Enumerable' because 'Enumerable' does not contain a public definition for 'GetEnumerator' Diagnostic(ErrorCode.ERR_ForEachMissingMember, "new Enumerable()").WithArguments("Enumerable", "GetEnumerator")); } [Fact] public void TestErrorPatternNonPublicGetEnumerator() { var text = @" class C { static void Main(string[] args) { foreach (int x in new Enumerable()) { } } } class Enumerable { internal Enumerator GetEnumerator() { return new Enumerator(); } } class Enumerator { public int Current { get { return 1; } } public bool MoveNext() { return false; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,27): warning CS0279: 'Enumerable' does not implement the 'collection' pattern. 'Enumerable.GetEnumerator()' is not a public instance or extension method. Diagnostic(ErrorCode.WRN_PatternNotPublicOrNotInstance, "new Enumerable()").WithArguments("Enumerable", "collection", "Enumerable.GetEnumerator()"), // (6,27): error CS1579: foreach statement cannot operate on variables of type 'Enumerable' because 'Enumerable' does not contain a public definition for 'GetEnumerator' Diagnostic(ErrorCode.ERR_ForEachMissingMember, "new Enumerable()").WithArguments("Enumerable", "GetEnumerator")); } [Fact] public void TestErrorPatternStaticGetEnumerator() { var text = @" class C { static void Main(string[] args) { foreach (int x in new Enumerable()) { } } } class Enumerable { public static Enumerator GetEnumerator() { return new Enumerator(); } } class Enumerator { public int Current { get { return 1; } } public bool MoveNext() { return false; } } "; CreateCompilation(text, parseOptions: TestOptions.Regular7).VerifyDiagnostics( // (6,27): warning CS0279: 'Enumerable' does not implement the 'collection' pattern. 'Enumerable.GetEnumerator()' is not a public instance or extension method. Diagnostic(ErrorCode.WRN_PatternNotPublicOrNotInstance, "new Enumerable()").WithArguments("Enumerable", "collection", "Enumerable.GetEnumerator()"), // (6,27): error CS1579: foreach statement cannot operate on variables of type 'Enumerable' because 'Enumerable' does not contain a public definition for 'GetEnumerator' Diagnostic(ErrorCode.ERR_ForEachMissingMember, "new Enumerable()").WithArguments("Enumerable", "GetEnumerator")); CreateCompilation(text).VerifyDiagnostics( // (6,27): error CS1579: foreach statement cannot operate on variables of type 'Enumerable' because 'Enumerable' does not contain a public instance or extension definition for 'GetEnumerator' Diagnostic(ErrorCode.ERR_ForEachMissingMember, "new Enumerable()").WithArguments("Enumerable", "GetEnumerator")); } [Fact] public void TestErrorPatternNullableGetEnumerator() { var text = @" struct C { static void Goo(Enumerable? e) { foreach (long x in e) { } } static void Main() { Goo(new Enumerable()); } } struct Enumerable { public Enumerator? GetEnumerator() { return new Enumerator(); } } struct Enumerator { public int Current { get { return 1; } } public bool MoveNext() { return false; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,28): error CS0117: 'Enumerator?' does not contain a definition for 'Current' Diagnostic(ErrorCode.ERR_NoSuchMember, "e").WithArguments("Enumerator?", "Current"), // (6,28): error CS0202: foreach requires that the return type 'Enumerator?' of 'Enumerable.GetEnumerator()' must have a suitable public MoveNext method and public Current property Diagnostic(ErrorCode.ERR_BadGetEnumerator, "e").WithArguments("Enumerator?", "Enumerable.GetEnumerator()")); } [Fact] public void TestErrorPatternNoCurrent() { var text = @" class C { static void Main(string[] args) { foreach (int x in new Enumerable()) { } } } class Enumerable { public Enumerator GetEnumerator() { return new Enumerator(); } } class Enumerator { //public int Current { get { return 1; } } public bool MoveNext() { return false; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,27): error CS0117: 'Enumerator' does not contain a definition for 'Current' Diagnostic(ErrorCode.ERR_NoSuchMember, "new Enumerable()").WithArguments("Enumerator", "Current"), // (6,27): error CS0202: foreach requires that the return type 'Enumerator' of 'Enumerable.GetEnumerator()' must have a suitable public MoveNext method and public Current property Diagnostic(ErrorCode.ERR_BadGetEnumerator, "new Enumerable()").WithArguments("Enumerator", "Enumerable.GetEnumerator()")); } [Fact] public void TestErrorPatternInaccessibleCurrent() { var text = @" class C { static void Main(string[] args) { foreach (int x in new Enumerable()) { } } } class Enumerable { public Enumerator GetEnumerator() { return new Enumerator(); } } class Enumerator { private int Current { get { return 1; } } public bool MoveNext() { return false; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,27): error CS0122: 'Enumerator.Current' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "new Enumerable()").WithArguments("Enumerator.Current"), // (6,27): error CS0202: foreach requires that the return type 'Enumerator' of 'Enumerable.GetEnumerator()' must have a suitable public MoveNext method and public Current property Diagnostic(ErrorCode.ERR_BadGetEnumerator, "new Enumerable()").WithArguments("Enumerator", "Enumerable.GetEnumerator()")); } [Fact] public void TestErrorPatternNonPublicCurrent() { var text = @" class C { static void Main(string[] args) { foreach (int x in new Enumerable()) { } } } class Enumerable { public Enumerator GetEnumerator() { return new Enumerator(); } } class Enumerator { internal int Current { get { return 1; } } public bool MoveNext() { return false; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,27): error CS0202: foreach requires that the return type 'Enumerator' of 'Enumerable.GetEnumerator()' must have a suitable public MoveNext method and public Current property Diagnostic(ErrorCode.ERR_BadGetEnumerator, "new Enumerable()").WithArguments("Enumerator", "Enumerable.GetEnumerator()")); } [Fact] public void TestErrorPatternStaticCurrent() { var text = @" class C { static void Main(string[] args) { foreach (int x in new Enumerable()) { } } } class Enumerable { public Enumerator GetEnumerator() { return new Enumerator(); } } class Enumerator { public static int Current { get { return 1; } } public bool MoveNext() { return false; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,27): error CS0202: foreach requires that the return type 'Enumerator' of 'Enumerable.GetEnumerator()' must have a suitable public MoveNext method and public Current property Diagnostic(ErrorCode.ERR_BadGetEnumerator, "new Enumerable()").WithArguments("Enumerator", "Enumerable.GetEnumerator()")); } [Fact] public void TestErrorPatternNonPropertyCurrent() { var text = @" class C { static void Main(string[] args) { foreach (int x in new Enumerable()) { } } } class Enumerable { public Enumerator GetEnumerator() { return new Enumerator(); } } class Enumerator { public int Current; public bool MoveNext() { return false; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,27): error CS0202: foreach requires that the return type 'Enumerator' of 'Enumerable.GetEnumerator()' must have a suitable public MoveNext method and public Current property // foreach (int x in new Enumerable()) Diagnostic(ErrorCode.ERR_BadGetEnumerator, "new Enumerable()").WithArguments("Enumerator", "Enumerable.GetEnumerator()"), // (19,16): warning CS0649: Field 'Enumerator.Current' is never assigned to, and will always have its default value 0 // public int Current; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Current").WithArguments("Enumerator.Current", "0") ); } [Fact] public void TestErrorPatternNoMoveNext() { var text = @" class C { static void Main(string[] args) { foreach (int x in new Enumerable()) { } } } class Enumerable { public Enumerator GetEnumerator() { return new Enumerator(); } } class Enumerator { public int Current { get { return 1; } } //public bool MoveNext() { return false; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,27): error CS0117: 'Enumerator' does not contain a definition for 'MoveNext' Diagnostic(ErrorCode.ERR_NoSuchMember, "new Enumerable()").WithArguments("Enumerator", "MoveNext"), // (6,27): error CS0202: foreach requires that the return type 'Enumerator' of 'Enumerable.GetEnumerator()' must have a suitable public MoveNext method and public Current property Diagnostic(ErrorCode.ERR_BadGetEnumerator, "new Enumerable()").WithArguments("Enumerator", "Enumerable.GetEnumerator()")); } [Fact] public void TestErrorPatternInaccessibleMoveNext() { var text = @" class C { static void Main(string[] args) { foreach (int x in new Enumerable()) { } } } class Enumerable { public Enumerator GetEnumerator() { return new Enumerator(); } } class Enumerator { public int Current { get { return 1; } } private bool MoveNext() { return false; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,27): error CS0122: 'Enumerator.MoveNext()' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "new Enumerable()").WithArguments("Enumerator.MoveNext()"), // (6,27): error CS0202: foreach requires that the return type 'Enumerator' of 'Enumerable.GetEnumerator()' must have a suitable public MoveNext method and public Current property Diagnostic(ErrorCode.ERR_BadGetEnumerator, "new Enumerable()").WithArguments("Enumerator", "Enumerable.GetEnumerator()")); } [Fact] public void TestErrorPatternNonPublicMoveNext() { var text = @" class C { static void Main(string[] args) { foreach (int x in new Enumerable()) { } } } class Enumerable { public Enumerator GetEnumerator() { return new Enumerator(); } } class Enumerator { public int Current { get { return 1; } } internal bool MoveNext() { return false; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,27): error CS0202: foreach requires that the return type 'Enumerator' of 'Enumerable.GetEnumerator()' must have a suitable public 'MoveNext' method and public 'Current' property // foreach (int x in new Enumerable()) Diagnostic(ErrorCode.ERR_BadGetEnumerator, "new Enumerable()").WithArguments("Enumerator", "Enumerable.GetEnumerator()").WithLocation(6, 27) ); } [Fact] public void TestErrorPatternStaticMoveNext() { var text = @" class C { static void Main(string[] args) { foreach (int x in new Enumerable()) { } } } class Enumerable { public Enumerator GetEnumerator() { return new Enumerator(); } } class Enumerator { public int Current { get { return 1; } } public static bool MoveNext() { return false; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,27): error CS0202: foreach requires that the return type 'Enumerator' of 'Enumerable.GetEnumerator()' must have a suitable public MoveNext method and public Current property Diagnostic(ErrorCode.ERR_BadGetEnumerator, "new Enumerable()").WithArguments("Enumerator", "Enumerable.GetEnumerator()")); } [Fact] public void TestErrorPatternNonMethodMoveNext() { var text = @" class C { static void Main(string[] args) { foreach (int x in new Enumerable()) { } } } class Enumerable { public Enumerator GetEnumerator() { return new Enumerator(); } } class Enumerator { public int Current { get { return 1; } } public bool MoveNext; } "; CreateCompilation(text).VerifyDiagnostics( // (6,27): error CS0202: foreach requires that the return type 'Enumerator' of 'Enumerable.GetEnumerator()' must have a suitable public MoveNext method and public Current property // foreach (int x in new Enumerable()) Diagnostic(ErrorCode.ERR_BadGetEnumerator, "new Enumerable()").WithArguments("Enumerator", "Enumerable.GetEnumerator()"), // (20,17): warning CS0649: Field 'Enumerator.MoveNext' is never assigned to, and will always have its default value false // public bool MoveNext; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "MoveNext").WithArguments("Enumerator.MoveNext", "false") ); } [Fact] public void TestErrorPatternNonBoolMoveNext() { var text = @" class C { static void Main(string[] args) { foreach (int x in new Enumerable()) { } } } class Enumerable { public Enumerator GetEnumerator() { return new Enumerator(); } } class Enumerator { public int Current { get { return 1; } } public int MoveNext() { return 1; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,27): error CS0202: foreach requires that the return type 'Enumerator' of 'Enumerable.GetEnumerator()' must have a suitable public MoveNext method and public Current property Diagnostic(ErrorCode.ERR_BadGetEnumerator, "new Enumerable()").WithArguments("Enumerator", "Enumerable.GetEnumerator()")); } [Fact] public void TestErrorPatternNullableBoolMoveNext() { var text = @" class C { static void Main(string[] args) { foreach (int x in new Enumerable()) { } } } class Enumerable { public Enumerator GetEnumerator() { return new Enumerator(); } } class Enumerator { public int Current { get { return 1; } } public bool? MoveNext() { return true; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,27): error CS0202: foreach requires that the return type 'Enumerator' of 'Enumerable.GetEnumerator()' must have a suitable public MoveNext method and public Current property Diagnostic(ErrorCode.ERR_BadGetEnumerator, "new Enumerable()").WithArguments("Enumerator", "Enumerable.GetEnumerator()")); } [Fact] public void TestErrorPatternNoMoveNextOrCurrent() { var text = @" class C { static void Main(string[] args) { foreach (int x in new Enumerable()) { } } } class Enumerable { public Enumerator GetEnumerator() { return new Enumerator(); } } class Enumerator { //public int Current { get { return 1; } } //public bool MoveNext() { return false; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,27): error CS0117: 'Enumerator' does not contain a definition for 'Current' Diagnostic(ErrorCode.ERR_NoSuchMember, "new Enumerable()").WithArguments("Enumerator", "Current"), // (6,27): error CS0202: foreach requires that the return type 'Enumerator' of 'Enumerable.GetEnumerator()' must have a suitable public MoveNext method and public Current property Diagnostic(ErrorCode.ERR_BadGetEnumerator, "new Enumerable()").WithArguments("Enumerator", "Enumerable.GetEnumerator()")); } [Fact] public void TestErrorMultipleIEnumerableT() { var text = @" using System.Collections; using System.Collections.Generic; class C { void Goo(Enumerable e) { foreach (int x in e) { } } } class Enumerable : IEnumerable<int>, IEnumerable<float> { IEnumerator<float> IEnumerable<float>.GetEnumerator() { throw null; } IEnumerator<int> IEnumerable<int>.GetEnumerator() { throw null; } IEnumerator IEnumerable.GetEnumerator() { throw null; } } "; CreateCompilation(text).VerifyDiagnostics( // (9,27): error CS1640: foreach statement cannot operate on variables of type 'Enumerable' because it implements multiple instantiations of 'System.Collections.Generic.IEnumerable<T>'; try casting to a specific interface instantiation Diagnostic(ErrorCode.ERR_MultipleIEnumOfT, "e").WithArguments("Enumerable", "System.Collections.Generic.IEnumerable<T>")); } [Fact] public void TestErrorMultipleIEnumerableT2() { var text = @" using System.Collections; using System.Collections.Generic; class C { void Goo(Enumerable e) { foreach (int x in e) { } } } class Enumerable : IEnumerable<int>, I { IEnumerator<float> IEnumerable<float>.GetEnumerator() { throw null; } IEnumerator<int> IEnumerable<int>.GetEnumerator() { throw null; } IEnumerator IEnumerable.GetEnumerator() { throw null; } } interface I : IEnumerable<float> { } "; CreateCompilation(text).VerifyDiagnostics( // (9,27): error CS1640: foreach statement cannot operate on variables of type 'Enumerable' because it implements multiple instantiations of 'System.Collections.Generic.IEnumerable<T>'; try casting to a specific interface instantiation Diagnostic(ErrorCode.ERR_MultipleIEnumOfT, "e").WithArguments("Enumerable", "System.Collections.Generic.IEnumerable<T>")); } /// <summary> /// Type parameter with constraints containing /// IEnumerable&lt;T&gt; with explicit implementations. /// </summary> [Fact] public void TestErrorExplicitIEnumerableTOnTypeParameter() { var text = @"using System.Collections; using System.Collections.Generic; struct S { } interface I : IEnumerable<S> { } class A : IEnumerable<int> { IEnumerator<int> IEnumerable<int>.GetEnumerator() { return null; } IEnumerator IEnumerable.GetEnumerator() { return null; } } class B : A, I { IEnumerator<S> IEnumerable<S>.GetEnumerator() { return null; } IEnumerator IEnumerable.GetEnumerator() { return null; } } class C { static void M<T1, T2, T3, T4, T5, T6>(A a, B b, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6) where T1 : A where T2 : B where T3 : I where T4 : T1, I where T5 : A, I where T6 : A, IEnumerable<string> { foreach (int o in a) { } foreach (var o in b) { } foreach (int o in t1) { } foreach (var o in t2) { } foreach (S o in t3) { } foreach (S o in t4) { } foreach (S o in t5) { } foreach (string o in t6) { } } }"; CreateCompilation(text).VerifyDiagnostics( // (26,27): error CS1640: foreach statement cannot operate on variables of type 'B' because it implements multiple instantiations of 'System.Collections.Generic.IEnumerable<T>'; try casting to a specific interface instantiation Diagnostic(ErrorCode.ERR_MultipleIEnumOfT, "b").WithArguments("B", "System.Collections.Generic.IEnumerable<T>").WithLocation(26, 27), // (28,27): error CS1640: foreach statement cannot operate on variables of type 'T2' because it implements multiple instantiations of 'System.Collections.Generic.IEnumerable<T>'; try casting to a specific interface instantiation Diagnostic(ErrorCode.ERR_MultipleIEnumOfT, "t2").WithArguments("T2", "System.Collections.Generic.IEnumerable<T>").WithLocation(28, 27)); } /// <summary> /// Type parameter with constraints containing /// IEnumerable&lt;T&gt; with implicit implementations. /// </summary> [Fact] public void TestErrorImplicitIEnumerableTOnTypeParameter() { var text = @"using System.Collections; using System.Collections.Generic; struct S { } interface I : IEnumerable<S> { } class A : IEnumerable<int> { public IEnumerator<int> GetEnumerator() { return null; } IEnumerator IEnumerable.GetEnumerator() { return null; } } class B : A, I { public new IEnumerator<S> GetEnumerator() { return null; } IEnumerator IEnumerable.GetEnumerator() { return null; } } class C { static void M<T1, T2, T3, T4, T5, T6>(A a, B b, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6) where T1 : A where T2 : B where T3 : I where T4 : T1, I where T5 : A, I where T6 : A, IEnumerable<string> { foreach (int o in a) { } foreach (var o in b) { } foreach (int o in t1) { } foreach (var o in t2) { } foreach (S o in t3) { } foreach (int o in t4) { } foreach (S o in t5) { } foreach (string o in t6) { } } }"; CreateCompilation(text).VerifyDiagnostics( // (31,9): error CS0030: Cannot convert type 'int' to 'S' Diagnostic(ErrorCode.ERR_NoExplicitConv, "foreach").WithArguments("int", "S").WithLocation(31, 9), // (32,9): error CS0030: Cannot convert type 'int' to 'string' Diagnostic(ErrorCode.ERR_NoExplicitConv, "foreach").WithArguments("int", "string").WithLocation(32, 9)); } /// <summary> /// Type parameter with constraints /// using enumerable pattern. /// </summary> [Fact] public void TestErrorEnumerablePatternOnTypeParameter() { var text = @"using System.Collections.Generic; interface I { IEnumerator<object> GetEnumerator(); } class E : I { IEnumerator<object> I.GetEnumerator() { return null; } } class C { static void M<T, U, V>(T t, U u, V v) where T : E where U : E, I where V : T, I { foreach (var o in t) { } foreach (var o in u) { } foreach (var o in v) { } } }"; CreateCompilation(text).VerifyDiagnostics( // (17,27): error CS1579: foreach statement cannot operate on variables of type 'T' because 'T' does not contain a public definition for 'GetEnumerator' Diagnostic(ErrorCode.ERR_ForEachMissingMember, "t").WithArguments("T", "GetEnumerator").WithLocation(17, 27)); } [Fact] public void TestErrorNonEnumerable() { var text = @" class C { void Goo(int i) { foreach (int x in i) { } } } "; CreateCompilation(text).VerifyDiagnostics( // (6,27): error CS1579: foreach statement cannot operate on variables of type 'int' because 'int' does not contain a public definition for 'GetEnumerator' Diagnostic(ErrorCode.ERR_ForEachMissingMember, "i").WithArguments("int", "GetEnumerator")); } [Fact] public void TestErrorModifyIterationVariable() { var text = @" class C { void Goo(int[] a) { foreach (int x in a) { x++; } } } "; CreateCompilation(text).VerifyDiagnostics( // (6,32): error CS1656: Cannot assign to 'x' because it is a 'foreach iteration variable' Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "x").WithArguments("x", "foreach iteration variable")); } [Fact] public void TestErrorImplicitlyTypedCycle() { var text = @" class C { System.Collections.IEnumerable Goo(object y) { foreach (var x in Goo(x)) { } return null; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,31): error CS0103: The name 'x' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x")); } [Fact] public void TestErrorDynamicEnumerator() { var text = @" class C { void Goo(DynamicEnumerable e) { foreach (int x in e) { } } } public class DynamicEnumerable { public dynamic GetEnumerator() { return null; } } "; // It's not entirely clear why this doesn't work, but it doesn't work in Dev10 either. CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (6,27): error CS0117: 'dynamic' does not contain a definition for 'Current' Diagnostic(ErrorCode.ERR_NoSuchMember, "e").WithArguments("dynamic", "Current"), // (6,27): error CS0202: foreach requires that the return type 'dynamic' of 'DynamicEnumerable.GetEnumerator()' must have a suitable public MoveNext method and public Current property Diagnostic(ErrorCode.ERR_BadGetEnumerator, "e").WithArguments("dynamic", "DynamicEnumerable.GetEnumerator()")); } [Fact] public void TestErrorTypeEnumerable() { var text = @" class C { static void Main() { foreach (var x in System.Collections.IEnumerable) { } } } "; // It's not entirely clear why this doesn't work, but it doesn't work in Dev10 either. CreateCompilation(text).VerifyDiagnostics( // (6,27): error CS0119: 'System.Collections.IEnumerable' is a 'type', which is not valid in the given context // foreach (var x in System.Collections.IEnumerable) { } Diagnostic(ErrorCode.ERR_BadSKunknown, "System.Collections.IEnumerable").WithArguments("System.Collections.IEnumerable", "type")); } [Fact] public void TestErrorTypeNonEnumerable() { var text = @" class C { void Goo() { foreach (int x in System.Console) { } } } "; // It's not entirely clear why this doesn't work, but it doesn't work in Dev10 either. CreateCompilation(text).VerifyDiagnostics( // (6,27): error CS0119: 'System.Console' is a 'type', which is not valid in the given context // foreach (int x in System.Console) { } Diagnostic(ErrorCode.ERR_BadSKunknown, "System.Console").WithArguments("System.Console", "type")); } [WorkItem(545123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545123")] [Fact] public void TestErrorForEachLoopWithSyntaxErrors() { string source = @" public static partial class Extensions { public static ((System.Linq.Expressions.Expression<System.Func<int>>)(() => int )).Compile()()Fib(this int i) { } } public class ExtensionMethodTest { public static void Run() { int i = 0; var Fib = new[] { i++.Fib() }; foreach (var j in Fib) { } } }"; Assert.NotEmpty(CreateCompilation(source).GetDiagnostics()); } [WorkItem(545123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545123")] [Fact] public void TestErrorForEachOverVoidArray1() { string source = @" class C { static void Main() { var array = new[] { Main() }; foreach (var element in array) { } } } "; CreateCompilation(source).VerifyDiagnostics( // (6,21): error CS0826: No best type found for implicitly-typed array // var array = new[] { Main() }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { Main() }")); } [WorkItem(545123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545123")] [Fact] public void TestErrorForEachOverVoidArray2() { string source = @" class C { static void Main() { var array = new[] { Main() }; foreach (int element in array) { } } } "; CreateCompilation(source).VerifyDiagnostics( // (6,21): error CS0826: No best type found for implicitly-typed array // var array = new[] { Main() }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { Main() }"), // CONSIDER: Could eliminate this cascading diagnostic. // (7,9): error CS0030: Cannot convert type '?' to 'int' // foreach (int element in array) Diagnostic(ErrorCode.ERR_NoExplicitConv, "foreach").WithArguments("?", "int")); } [WorkItem(545123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545123")] [Fact] public void TestErrorForEachWithVoidIterationVariable() { string source = @" class C { static void Main() { foreach (void element in new int[1]) { } } } "; CreateCompilation(source).VerifyDiagnostics( // (6,18): error CS1547: Keyword 'void' cannot be used in this context // foreach (void element in new int[1]) Diagnostic(ErrorCode.ERR_NoVoidHere, "void").WithLocation(6, 18), // (6,9): error CS0030: Cannot convert type 'int' to 'void' // foreach (void element in new int[1]) Diagnostic(ErrorCode.ERR_NoExplicitConv, "foreach").WithArguments("int", "void").WithLocation(6, 9) ); } [WorkItem(545123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545123")] [Fact] public void TestErrorForEachOverErrorTypeArray() { string source = @" class C { static void Main() { foreach (var element in new Unknown[1]) { } } } "; CreateCompilation(source).VerifyDiagnostics( // (6,37): error CS0246: The type or namespace name 'Unknown' could not be found (are you missing a using directive or an assembly reference?) // foreach (var element in new Unknown[1]) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Unknown").WithArguments("Unknown")); } [Fact] public void TestSuccessArray() { var text = @" class C { void Goo(int[] a) { foreach (int x in a) { } } } "; var boundNode = GetBoundForEachStatement(text); ForEachEnumeratorInfo info = boundNode.EnumeratorInfoOpt; Assert.NotNull(info); Assert.Equal("System.Collections.IEnumerable", info.CollectionType.ToTestDisplayString()); //NB: differs from expression type Assert.Equal(SpecialType.System_Int32, info.ElementTypeWithAnnotations.SpecialType); Assert.Equal("System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()", info.GetEnumeratorInfo.Method.ToTestDisplayString()); Assert.Empty(info.GetEnumeratorInfo.Arguments); Assert.Equal("System.Object System.Collections.IEnumerator.Current.get", info.CurrentPropertyGetter.ToTestDisplayString()); Assert.Equal("System.Boolean System.Collections.IEnumerator.MoveNext()", info.MoveNextInfo.Method.ToTestDisplayString()); Assert.Empty(info.MoveNextInfo.Arguments); Assert.True(info.NeedsDisposal); Assert.Equal(ConversionKind.ImplicitReference, info.CollectionConversion.Kind); Assert.Equal(ConversionKind.Unboxing, info.CurrentConversion.Kind); Assert.Equal(ConversionKind.ImplicitReference, info.EnumeratorConversion.Kind); Assert.Equal(ConversionKind.Identity, boundNode.ElementConversion.Kind); Assert.Equal("System.Int32 x", boundNode.IterationVariables.Single().ToTestDisplayString()); Assert.Equal(SpecialType.System_Collections_IEnumerable, boundNode.Expression.Type.SpecialType); Assert.Equal(SymbolKind.ArrayType, ((BoundConversion)boundNode.Expression).Operand.Type.Kind); } [Fact] public void TestSuccessString() { var text = @" class C { void Goo(string s) { foreach (char c in s) { } } } "; var boundNode = GetBoundForEachStatement(text); ForEachEnumeratorInfo info = boundNode.EnumeratorInfoOpt; Assert.NotNull(info); Assert.Equal(SpecialType.System_String, info.CollectionType.SpecialType); Assert.Equal(SpecialType.System_Char, info.ElementTypeWithAnnotations.SpecialType); Assert.Equal("System.CharEnumerator System.String.GetEnumerator()", info.GetEnumeratorInfo.Method.ToTestDisplayString()); Assert.Empty(info.GetEnumeratorInfo.Arguments); Assert.Equal("System.Char System.CharEnumerator.Current.get", info.CurrentPropertyGetter.ToTestDisplayString()); Assert.Equal("System.Boolean System.CharEnumerator.MoveNext()", info.MoveNextInfo.Method.ToTestDisplayString()); Assert.Empty(info.MoveNextInfo.Arguments); Assert.True(info.NeedsDisposal); Assert.Equal(ConversionKind.Identity, info.CollectionConversion.Kind); Assert.Equal(ConversionKind.Identity, info.CurrentConversion.Kind); Assert.Equal(ConversionKind.ImplicitReference, info.EnumeratorConversion.Kind); Assert.Equal(ConversionKind.Identity, boundNode.ElementConversion.Kind); Assert.Equal("System.Char c", boundNode.IterationVariables.Single().ToTestDisplayString()); Assert.Equal(SpecialType.System_String, boundNode.Expression.Type.SpecialType); Assert.Equal(SpecialType.System_String, ((BoundConversion)boundNode.Expression).Operand.Type.SpecialType); } [Fact] public void TestSuccessPattern() { var text = @" class C { void Goo(Enumerable e) { foreach (long x in e) { } } } class Enumerable { public Enumerator GetEnumerator() { return new Enumerator(); } } class Enumerator { public int Current { get { return 1; } } public bool MoveNext() { return false; } } "; var boundNode = GetBoundForEachStatement(text); ForEachEnumeratorInfo info = boundNode.EnumeratorInfoOpt; Assert.NotNull(info); Assert.Equal("Enumerable", info.CollectionType.ToTestDisplayString()); Assert.Equal(SpecialType.System_Int32, info.ElementTypeWithAnnotations.SpecialType); Assert.Equal("Enumerator Enumerable.GetEnumerator()", info.GetEnumeratorInfo.Method.ToTestDisplayString()); Assert.Empty(info.GetEnumeratorInfo.Arguments); Assert.Equal("System.Int32 Enumerator.Current.get", info.CurrentPropertyGetter.ToTestDisplayString()); Assert.Equal("System.Boolean Enumerator.MoveNext()", info.MoveNextInfo.Method.ToTestDisplayString()); Assert.Empty(info.MoveNextInfo.Arguments); Assert.True(info.NeedsDisposal); Assert.Equal(ConversionKind.Identity, info.CollectionConversion.Kind); Assert.Equal(ConversionKind.Identity, info.CurrentConversion.Kind); Assert.Equal(ConversionKind.ImplicitReference, info.EnumeratorConversion.Kind); Assert.Equal(ConversionKind.ImplicitNumeric, boundNode.ElementConversion.Kind); Assert.Equal("System.Int64 x", boundNode.IterationVariables.Single().ToTestDisplayString()); Assert.Equal("Enumerable", boundNode.Expression.Type.ToTestDisplayString()); Assert.Equal("Enumerable", ((BoundConversion)boundNode.Expression).Operand.Type.ToTestDisplayString()); } [Fact] public void TestSuccessPatternStruct() { var text = @" struct C { void Goo(Enumerable e) { foreach (long x in e) { } } } struct Enumerable { public Enumerator GetEnumerator() { return new Enumerator(); } } struct Enumerator { public int Current { get { return 1; } } public bool MoveNext() { return false; } } "; var boundNode = GetBoundForEachStatement(text); ForEachEnumeratorInfo info = boundNode.EnumeratorInfoOpt; Assert.NotNull(info); Assert.Equal("Enumerable", info.CollectionType.ToTestDisplayString()); Assert.Equal(SpecialType.System_Int32, info.ElementTypeWithAnnotations.SpecialType); Assert.Equal("Enumerator Enumerable.GetEnumerator()", info.GetEnumeratorInfo.Method.ToTestDisplayString()); Assert.Empty(info.GetEnumeratorInfo.Arguments); Assert.Equal("System.Int32 Enumerator.Current.get", info.CurrentPropertyGetter.ToTestDisplayString()); Assert.Equal("System.Boolean Enumerator.MoveNext()", info.MoveNextInfo.Method.ToTestDisplayString()); Assert.Empty(info.MoveNextInfo.Arguments); Assert.False(info.NeedsDisposal); // Definitely not disposable Assert.Equal(ConversionKind.Identity, info.CollectionConversion.Kind); Assert.Equal(ConversionKind.Identity, info.CurrentConversion.Kind); Assert.Equal(ConversionKind.Identity, info.EnumeratorConversion.Kind); Assert.Equal(ConversionKind.ImplicitNumeric, boundNode.ElementConversion.Kind); Assert.Equal("System.Int64 x", boundNode.IterationVariables.Single().ToTestDisplayString()); Assert.Equal("Enumerable", boundNode.Expression.Type.ToTestDisplayString()); Assert.Equal("Enumerable", ((BoundConversion)boundNode.Expression).Operand.Type.ToTestDisplayString()); } [Fact] public void TestSuccessInterfacePattern() { var text = @" class C { void Goo(System.Collections.IEnumerable e) { foreach (long x in e) { } } } "; var boundNode = GetBoundForEachStatement(text); ForEachEnumeratorInfo info = boundNode.EnumeratorInfoOpt; Assert.NotNull(info); Assert.Equal("System.Collections.IEnumerable", info.CollectionType.ToTestDisplayString()); Assert.Equal(SpecialType.System_Object, info.ElementTypeWithAnnotations.SpecialType); Assert.Equal("System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()", info.GetEnumeratorInfo.Method.ToTestDisplayString()); Assert.Empty(info.GetEnumeratorInfo.Arguments); Assert.Equal("System.Object System.Collections.IEnumerator.Current.get", info.CurrentPropertyGetter.ToTestDisplayString()); Assert.Equal("System.Boolean System.Collections.IEnumerator.MoveNext()", info.MoveNextInfo.Method.ToTestDisplayString()); Assert.Empty(info.MoveNextInfo.Arguments); Assert.True(info.NeedsDisposal); Assert.Equal(ConversionKind.Identity, info.CollectionConversion.Kind); Assert.Equal(ConversionKind.Identity, info.CurrentConversion.Kind); Assert.Equal(ConversionKind.ImplicitReference, info.EnumeratorConversion.Kind); Assert.Equal(ConversionKind.Unboxing, boundNode.ElementConversion.Kind); Assert.Equal("System.Int64 x", boundNode.IterationVariables.Single().ToTestDisplayString()); Assert.Equal("System.Collections.IEnumerable", boundNode.Expression.Type.ToTestDisplayString()); Assert.Equal("System.Collections.IEnumerable", ((BoundConversion)boundNode.Expression).Operand.Type.ToTestDisplayString()); } [Fact] public void TestSuccessInterfaceNonPatternGeneric() { var text = @" class C { void Goo(Enumerable e) { foreach (long x in e) { } } } class Enumerable : System.Collections.Generic.IEnumerable<int> { // Explicit implementations won't match pattern. System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return null; } System.Collections.Generic.IEnumerator<int> System.Collections.Generic.IEnumerable<int>.GetEnumerator() { return null; } } "; var boundNode = GetBoundForEachStatement(text); ForEachEnumeratorInfo info = boundNode.EnumeratorInfoOpt; Assert.NotNull(info); Assert.Equal("System.Collections.Generic.IEnumerable<System.Int32>", info.CollectionType.ToTestDisplayString()); //NB: differs from expression type Assert.Equal(SpecialType.System_Int32, info.ElementTypeWithAnnotations.SpecialType); Assert.Equal("System.Collections.Generic.IEnumerator<System.Int32> System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator()", info.GetEnumeratorInfo.Method.ToTestDisplayString()); Assert.Empty(info.GetEnumeratorInfo.Arguments); Assert.Equal("System.Int32 System.Collections.Generic.IEnumerator<System.Int32>.Current.get", info.CurrentPropertyGetter.ToTestDisplayString()); Assert.Equal("System.Boolean System.Collections.IEnumerator.MoveNext()", info.MoveNextInfo.Method.ToTestDisplayString()); //NB: not on generic interface Assert.Empty(info.MoveNextInfo.Arguments); Assert.True(info.NeedsDisposal); Assert.Equal(ConversionKind.ImplicitReference, info.CollectionConversion.Kind); Assert.Equal(ConversionKind.Identity, info.CurrentConversion.Kind); Assert.Equal(ConversionKind.ImplicitReference, info.EnumeratorConversion.Kind); Assert.Equal(ConversionKind.ImplicitNumeric, boundNode.ElementConversion.Kind); Assert.Equal("System.Int64 x", boundNode.IterationVariables.Single().ToTestDisplayString()); Assert.Equal("System.Collections.Generic.IEnumerable<System.Int32>", boundNode.Expression.Type.ToTestDisplayString()); Assert.Equal("Enumerable", ((BoundConversion)boundNode.Expression).Operand.Type.ToTestDisplayString()); } [Fact] public void TestSuccessInterfaceNonPatternInaccessibleGeneric() { var text = @" class C { void Goo(Enumerable e) { foreach (object x in e) { } } } class Enumerable : System.Collections.Generic.IEnumerable<Enumerable.Hidden> { // Explicit implementations won't match pattern. System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return null; } System.Collections.Generic.IEnumerator<Hidden> System.Collections.Generic.IEnumerable<Hidden>.GetEnumerator() { return null; } private class Hidden { } } "; var boundNode = GetBoundForEachStatement(text); ForEachEnumeratorInfo info = boundNode.EnumeratorInfoOpt; Assert.NotNull(info); Assert.Equal("System.Collections.IEnumerable", info.CollectionType.ToTestDisplayString()); //NB: fall back on non-generic, since generic is inaccessible Assert.Equal(SpecialType.System_Object, info.ElementTypeWithAnnotations.SpecialType); Assert.Equal("System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()", info.GetEnumeratorInfo.Method.ToTestDisplayString()); Assert.Empty(info.GetEnumeratorInfo.Arguments); Assert.Equal("System.Object System.Collections.IEnumerator.Current.get", info.CurrentPropertyGetter.ToTestDisplayString()); Assert.Equal("System.Boolean System.Collections.IEnumerator.MoveNext()", info.MoveNextInfo.Method.ToTestDisplayString()); Assert.Empty(info.MoveNextInfo.Arguments); Assert.True(info.NeedsDisposal); Assert.Equal(ConversionKind.ImplicitReference, info.CollectionConversion.Kind); Assert.Equal(ConversionKind.Identity, info.CurrentConversion.Kind); Assert.Equal(ConversionKind.ImplicitReference, info.EnumeratorConversion.Kind); Assert.Equal(ConversionKind.Identity, boundNode.ElementConversion.Kind); Assert.Equal("System.Object x", boundNode.IterationVariables.Single().ToTestDisplayString()); Assert.Equal(SpecialType.System_Collections_IEnumerable, boundNode.Expression.Type.SpecialType); Assert.Equal("Enumerable", ((BoundConversion)boundNode.Expression).Operand.Type.ToTestDisplayString()); } [Fact] public void TestSuccessInterfaceNonPatternNonGeneric() { var text = @" class C { void Goo(Enumerable e) { foreach (long x in e) { } } } class Enumerable : System.Collections.IEnumerable { // Explicit implementation won't match pattern. System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return null; } } "; var boundNode = GetBoundForEachStatement(text); ForEachEnumeratorInfo info = boundNode.EnumeratorInfoOpt; Assert.NotNull(info); Assert.Equal("System.Collections.IEnumerable", info.CollectionType.ToTestDisplayString()); //NB: differs from expression type Assert.Equal(SpecialType.System_Object, info.ElementTypeWithAnnotations.SpecialType); Assert.Equal("System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()", info.GetEnumeratorInfo.Method.ToTestDisplayString()); Assert.Empty(info.GetEnumeratorInfo.Arguments); Assert.Equal("System.Object System.Collections.IEnumerator.Current.get", info.CurrentPropertyGetter.ToTestDisplayString()); Assert.Equal("System.Boolean System.Collections.IEnumerator.MoveNext()", info.MoveNextInfo.Method.ToTestDisplayString()); Assert.Empty(info.MoveNextInfo.Arguments); Assert.True(info.NeedsDisposal); Assert.Equal(ConversionKind.ImplicitReference, info.CollectionConversion.Kind); Assert.Equal(ConversionKind.Identity, info.CurrentConversion.Kind); Assert.Equal(ConversionKind.ImplicitReference, info.EnumeratorConversion.Kind); Assert.Equal(ConversionKind.Unboxing, boundNode.ElementConversion.Kind); Assert.Equal("System.Int64 x", boundNode.IterationVariables.Single().ToTestDisplayString()); Assert.Equal(SpecialType.System_Collections_IEnumerable, boundNode.Expression.Type.SpecialType); Assert.Equal("Enumerable", ((BoundConversion)boundNode.Expression).Operand.Type.ToTestDisplayString()); } [Fact] public void TestSuccessImplicitlyTypedArray() { var text = @" class C { void Goo(int[] a) { foreach (var x in a) { } } } "; var boundNode = GetBoundForEachStatement(text); ForEachEnumeratorInfo info = boundNode.EnumeratorInfoOpt; Assert.NotNull(info); Assert.Equal("System.Collections.IEnumerable", info.CollectionType.ToTestDisplayString()); //NB: differs from expression type Assert.Equal(SpecialType.System_Int32, info.ElementTypeWithAnnotations.SpecialType); Assert.Equal("System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()", info.GetEnumeratorInfo.Method.ToTestDisplayString()); Assert.Empty(info.GetEnumeratorInfo.Arguments); Assert.Equal("System.Object System.Collections.IEnumerator.Current.get", info.CurrentPropertyGetter.ToTestDisplayString()); Assert.Equal("System.Boolean System.Collections.IEnumerator.MoveNext()", info.MoveNextInfo.Method.ToTestDisplayString()); Assert.Empty(info.MoveNextInfo.Arguments); Assert.True(info.NeedsDisposal); Assert.Equal(ConversionKind.ImplicitReference, info.CollectionConversion.Kind); Assert.Equal(ConversionKind.Unboxing, info.CurrentConversion.Kind); Assert.Equal(ConversionKind.ImplicitReference, info.EnumeratorConversion.Kind); Assert.Equal(ConversionKind.Identity, boundNode.ElementConversion.Kind); Assert.Equal(SpecialType.System_Int32, boundNode.IterationVariables.Single().Type.SpecialType); } [Fact] public void TestSuccessImplicitlyTypedString() { var text = @" class C { void Goo(string s) { foreach (var x in s) { } } } "; var boundNode = GetBoundForEachStatement(text); ForEachEnumeratorInfo info = boundNode.EnumeratorInfoOpt; Assert.NotNull(info); Assert.Equal(SpecialType.System_String, info.CollectionType.SpecialType); Assert.Equal(SpecialType.System_Char, info.ElementTypeWithAnnotations.SpecialType); Assert.Equal("System.CharEnumerator System.String.GetEnumerator()", info.GetEnumeratorInfo.Method.ToTestDisplayString()); Assert.Empty(info.GetEnumeratorInfo.Arguments); Assert.Equal("System.Char System.CharEnumerator.Current.get", info.CurrentPropertyGetter.ToTestDisplayString()); Assert.Equal("System.Boolean System.CharEnumerator.MoveNext()", info.MoveNextInfo.Method.ToTestDisplayString()); Assert.Empty(info.MoveNextInfo.Arguments); Assert.True(info.NeedsDisposal); Assert.Equal(ConversionKind.Identity, info.CollectionConversion.Kind); Assert.Equal(ConversionKind.Identity, info.CurrentConversion.Kind); Assert.Equal(ConversionKind.ImplicitReference, info.EnumeratorConversion.Kind); Assert.Equal(ConversionKind.Identity, boundNode.ElementConversion.Kind); Assert.Equal(SpecialType.System_Char, boundNode.IterationVariables.Single().Type.SpecialType); } [Fact] public void TestSuccessImplicitlyTypedPattern() { var text = @" class C { void Goo(Enumerable e) { foreach (var x in e) { } } } class Enumerable { public Enumerator GetEnumerator() { return new Enumerator(); } } class Enumerator { public int Current { get { return 1; } } public bool MoveNext() { return false; } } "; var boundNode = GetBoundForEachStatement(text); Assert.NotNull(boundNode.EnumeratorInfoOpt); Assert.Equal(ConversionKind.Identity, boundNode.ElementConversion.Kind); Assert.Equal(SpecialType.System_Int32, boundNode.IterationVariables.Single().Type.SpecialType); } [Fact] public void TestSuccessImplicitlyTypedInterface() { var text = @" class C { void Goo(Enumerable e) { foreach (var x in e) { } } } class Enumerable : System.Collections.IEnumerable { // Explicit implementation won't match pattern. System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return null; } } "; var boundNode = GetBoundForEachStatement(text); Assert.NotNull(boundNode.EnumeratorInfoOpt); Assert.Equal(ConversionKind.Identity, boundNode.ElementConversion.Kind); Assert.Equal(SpecialType.System_Object, boundNode.IterationVariables.Single().Type.SpecialType); } [Fact] public void TestSuccessExplicitlyTypedVar() { var text = @" class C { void Goo(var[] a) { foreach (var x in a) { } } class var { } } "; var boundNode = GetBoundForEachStatement(text); ForEachEnumeratorInfo info = boundNode.EnumeratorInfoOpt; Assert.NotNull(info); Assert.Equal("System.Collections.IEnumerable", info.CollectionType.ToTestDisplayString()); //NB: differs from expression type Assert.Equal("C.var", info.ElementTypeWithAnnotations.ToTestDisplayString()); Assert.Equal("System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()", info.GetEnumeratorInfo.Method.ToTestDisplayString()); Assert.Empty(info.GetEnumeratorInfo.Arguments); Assert.Equal("System.Object System.Collections.IEnumerator.Current.get", info.CurrentPropertyGetter.ToTestDisplayString()); Assert.Equal("System.Boolean System.Collections.IEnumerator.MoveNext()", info.MoveNextInfo.Method.ToTestDisplayString()); Assert.Empty(info.MoveNextInfo.Arguments); Assert.True(info.NeedsDisposal); Assert.Equal(ConversionKind.ImplicitReference, info.CollectionConversion.Kind); Assert.Equal(ConversionKind.ExplicitReference, info.CurrentConversion.Kind); //object to C.var Assert.Equal(ConversionKind.ImplicitReference, info.EnumeratorConversion.Kind); Assert.Equal(ConversionKind.Identity, boundNode.ElementConversion.Kind); Assert.Equal("C.var", boundNode.IterationVariables.Single().TypeWithAnnotations.ToTestDisplayString()); } [Fact] public void TestSuccessDynamicEnumerable() { var text = @" class C { void Goo(dynamic d) { foreach (int x in d) { } } } "; var boundNode = GetBoundForEachStatement(text); ForEachEnumeratorInfo info = boundNode.EnumeratorInfoOpt; Assert.NotNull(info); Assert.Equal(SpecialType.System_Collections_IEnumerable, info.CollectionType.SpecialType); Assert.Equal(SpecialType.System_Object, info.ElementTypeWithAnnotations.SpecialType); Assert.Equal("System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()", info.GetEnumeratorInfo.Method.ToTestDisplayString()); Assert.Empty(info.GetEnumeratorInfo.Arguments); Assert.Equal("System.Object System.Collections.IEnumerator.Current.get", info.CurrentPropertyGetter.ToTestDisplayString()); Assert.Equal("System.Boolean System.Collections.IEnumerator.MoveNext()", info.MoveNextInfo.Method.ToTestDisplayString()); Assert.Empty(info.MoveNextInfo.Arguments); Assert.True(info.NeedsDisposal); Assert.Equal(ConversionKind.ImplicitDynamic, info.CollectionConversion.Kind); Assert.Equal(ConversionKind.Identity, info.CurrentConversion.Kind); Assert.Equal(ConversionKind.ImplicitReference, info.EnumeratorConversion.Kind); Assert.Equal(ConversionKind.ExplicitDynamic, boundNode.ElementConversion.Kind); Assert.Equal("System.Int32 x", boundNode.IterationVariables.Single().ToTestDisplayString()); Assert.Equal(SpecialType.System_Collections_IEnumerable, boundNode.Expression.Type.SpecialType); Assert.Equal(TypeKind.Dynamic, ((BoundConversion)boundNode.Expression).Operand.Type.TypeKind); } [Fact] public void TestSuccessImplicitlyTypedDynamicEnumerable() { var text = @" class C { void Goo(dynamic d) { foreach (var x in d) { } } } "; var boundNode = GetBoundForEachStatement(text); ForEachEnumeratorInfo info = boundNode.EnumeratorInfoOpt; Assert.NotNull(info); Assert.Equal(SpecialType.System_Collections_IEnumerable, info.CollectionType.SpecialType); Assert.Equal(TypeKind.Dynamic, info.ElementType.TypeKind); //NB: differs from explicit case Assert.Equal("System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()", info.GetEnumeratorInfo.Method.ToTestDisplayString()); Assert.Empty(info.GetEnumeratorInfo.Arguments); Assert.Equal("System.Object System.Collections.IEnumerator.Current.get", info.CurrentPropertyGetter.ToTestDisplayString()); Assert.Equal("System.Boolean System.Collections.IEnumerator.MoveNext()", info.MoveNextInfo.Method.ToTestDisplayString()); Assert.Empty(info.MoveNextInfo.Arguments); Assert.True(info.NeedsDisposal); Assert.Equal(ConversionKind.ImplicitDynamic, info.CollectionConversion.Kind); Assert.Equal(ConversionKind.Identity, info.CurrentConversion.Kind); Assert.Equal(ConversionKind.ImplicitReference, info.EnumeratorConversion.Kind); Assert.Equal(ConversionKind.Identity, boundNode.ElementConversion.Kind); //NB: differs from explicit case Assert.Equal("dynamic x", boundNode.IterationVariables.Single().ToTestDisplayString()); Assert.Equal(SpecialType.System_Collections_IEnumerable, boundNode.Expression.Type.SpecialType); Assert.Equal(SymbolKind.DynamicType, ((BoundConversion)boundNode.Expression).Operand.Type.Kind); } [Fact] public void TestSuccessTypeParameterConstrainedToInterface() { var text = @" class C { static void Test<T>() where T : System.Collections.IEnumerator { foreach (object x in new Enumerable<T>()) { System.Console.WriteLine(x); } } } public class Enumerable<T> { public T GetEnumerator() { return default(T); } } "; var boundNode = GetBoundForEachStatement(text); ForEachEnumeratorInfo info = boundNode.EnumeratorInfoOpt; Assert.NotNull(info); Assert.Equal("Enumerable<T>", info.CollectionType.ToTestDisplayString()); Assert.Equal(SpecialType.System_Object, info.ElementTypeWithAnnotations.SpecialType); Assert.Equal("T Enumerable<T>.GetEnumerator()", info.GetEnumeratorInfo.Method.ToTestDisplayString()); Assert.Empty(info.GetEnumeratorInfo.Arguments); Assert.Equal("System.Object System.Collections.IEnumerator.Current.get", info.CurrentPropertyGetter.ToTestDisplayString()); Assert.Equal("System.Boolean System.Collections.IEnumerator.MoveNext()", info.MoveNextInfo.Method.ToTestDisplayString()); Assert.Empty(info.MoveNextInfo.Arguments); Assert.True(info.NeedsDisposal); Assert.Equal(ConversionKind.Identity, info.CollectionConversion.Kind); Assert.Equal(ConversionKind.Identity, info.CurrentConversion.Kind); Assert.Equal(ConversionKind.Boxing, info.EnumeratorConversion.Kind); Assert.Equal(ConversionKind.Identity, boundNode.ElementConversion.Kind); Assert.Equal("System.Object x", boundNode.IterationVariables.Single().ToTestDisplayString()); Assert.Equal("Enumerable<T>", boundNode.Expression.Type.ToTestDisplayString()); Assert.Equal("Enumerable<T>", ((BoundConversion)boundNode.Expression).Operand.Type.ToTestDisplayString()); } [Fact] public void TestSuccessTypeParameterConstrainedToClass() { var text = @"using System.Collections; using System.Collections.Generic; class A<T> : IEnumerable<T> { IEnumerator<T> IEnumerable<T>.GetEnumerator() { return null; } IEnumerator IEnumerable.GetEnumerator() { return null; } } class A0 : A<string> { } class C<T> { static void M<U, V>(A0 a, U u, V v) where U : A0 where V : A<T> { foreach (var o in a) { M<string>(o); } foreach (var o in u) { M<string>(o); } foreach (var o in v) { M<T>(o); } } static void M<U>(U u) { } }"; var compilation = CreateCompilation(text); compilation.VerifyDiagnostics(); } [Fact] public void TestSuccessTypeParameterConstrainedToPattern() { var text = @" class C { static void Test<T>() where T : MyEnumerator { foreach (object x in new Enumerable<T>()) { System.Console.WriteLine(x); } } } public class Enumerable<T> { public T GetEnumerator() { return default(T); } } interface MyEnumerator { object Current { get; } bool MoveNext(); } "; var boundNode = GetBoundForEachStatement(text); ForEachEnumeratorInfo info = boundNode.EnumeratorInfoOpt; Assert.NotNull(info); Assert.Equal("Enumerable<T>", info.CollectionType.ToTestDisplayString()); Assert.Equal(SpecialType.System_Object, info.ElementTypeWithAnnotations.SpecialType); Assert.Equal("T Enumerable<T>.GetEnumerator()", info.GetEnumeratorInfo.Method.ToTestDisplayString()); Assert.Empty(info.GetEnumeratorInfo.Arguments); Assert.Equal("System.Object MyEnumerator.Current.get", info.CurrentPropertyGetter.ToTestDisplayString()); Assert.Equal("System.Boolean MyEnumerator.MoveNext()", info.MoveNextInfo.Method.ToTestDisplayString()); Assert.Empty(info.MoveNextInfo.Arguments); Assert.True(info.NeedsDisposal); Assert.Equal(ConversionKind.Identity, info.CollectionConversion.Kind); Assert.Equal(ConversionKind.Identity, info.CurrentConversion.Kind); Assert.Equal(ConversionKind.Boxing, info.EnumeratorConversion.Kind); Assert.Equal(ConversionKind.Identity, boundNode.ElementConversion.Kind); Assert.Equal("System.Object x", boundNode.IterationVariables.Single().ToTestDisplayString()); Assert.Equal("Enumerable<T>", boundNode.Expression.Type.ToTestDisplayString()); Assert.Equal("Enumerable<T>", ((BoundConversion)boundNode.Expression).Operand.Type.ToTestDisplayString()); } // Copied from TestSuccessPatternStruct - only change is that Goo parameter is now nullable. [WorkItem(544908, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544908")] [Fact] public void TestSuccessNullableCollection() { var text = @" struct C { void Goo(Enumerable? e) { foreach (long x in e) { } } } struct Enumerable { public Enumerator GetEnumerator() { return new Enumerator(); } } struct Enumerator { public int Current { get { return 1; } } public bool MoveNext() { return false; } } "; var boundNode = GetBoundForEachStatement(text); // NOTE: info is exactly as if the collection was not nullable. ForEachEnumeratorInfo info = boundNode.EnumeratorInfoOpt; Assert.NotNull(info); Assert.Equal("Enumerable", info.CollectionType.ToTestDisplayString()); Assert.Equal(SpecialType.System_Int32, info.ElementTypeWithAnnotations.SpecialType); Assert.Equal("Enumerator Enumerable.GetEnumerator()", info.GetEnumeratorInfo.Method.ToTestDisplayString()); Assert.Empty(info.GetEnumeratorInfo.Arguments); Assert.Equal("System.Int32 Enumerator.Current.get", info.CurrentPropertyGetter.ToTestDisplayString()); Assert.Equal("System.Boolean Enumerator.MoveNext()", info.MoveNextInfo.Method.ToTestDisplayString()); Assert.Empty(info.MoveNextInfo.Arguments); Assert.False(info.NeedsDisposal); // Definitely not disposable Assert.Equal(ConversionKind.Identity, info.CollectionConversion.Kind); Assert.Equal(ConversionKind.Identity, info.CurrentConversion.Kind); Assert.Equal(ConversionKind.Identity, info.EnumeratorConversion.Kind); Assert.Equal(ConversionKind.ImplicitNumeric, boundNode.ElementConversion.Kind); Assert.Equal("System.Int64 x", boundNode.IterationVariables.Single().ToTestDisplayString()); Assert.Equal("Enumerable", boundNode.Expression.Type.ToTestDisplayString()); Assert.Equal("Enumerable", ((BoundConversion)boundNode.Expression).Operand.Type.ToTestDisplayString()); } [WorkItem(542193, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542193")] [Fact] public void ForEachStmtWithSyntaxError1() { var text = @" public class Test { public static void Main(string [] args) { foreach(int; i < 5; i++) { } } } "; var boundNode = GetBoundForEachStatement(text, TestOptions.Regular, // (6,13): error CS1525: Invalid expression term 'int' // foreach(int; i < 5; i++) Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(6, 13), // (6,16): error CS1515: 'in' expected // foreach(int; i < 5; i++) Diagnostic(ErrorCode.ERR_InExpected, ";").WithLocation(6, 16), // (6,16): error CS0230: Type and identifier are both required in a foreach statement // foreach(int; i < 5; i++) Diagnostic(ErrorCode.ERR_BadForeachDecl, ";").WithLocation(6, 16), // (6,16): error CS1525: Invalid expression term ';' // foreach(int; i < 5; i++) Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(6, 16), // (6,16): error CS1026: ) expected // foreach(int; i < 5; i++) Diagnostic(ErrorCode.ERR_CloseParenExpected, ";").WithLocation(6, 16), // (6,28): error CS1002: ; expected // foreach(int; i < 5; i++) Diagnostic(ErrorCode.ERR_SemicolonExpected, ")").WithLocation(6, 28), // (6,28): error CS1513: } expected // foreach(int; i < 5; i++) Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(6, 28), // (6,18): error CS0103: The name 'i' does not exist in the current context // foreach(int; i < 5; i++) Diagnostic(ErrorCode.ERR_NameNotInContext, "i").WithArguments("i").WithLocation(6, 18), // (6,18): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // foreach(int; i < 5; i++) Diagnostic(ErrorCode.ERR_IllegalStatement, "i < 5").WithLocation(6, 18), // (6,25): error CS0103: The name 'i' does not exist in the current context // foreach(int; i < 5; i++) Diagnostic(ErrorCode.ERR_NameNotInContext, "i").WithArguments("i").WithLocation(6, 25)); Assert.Null(boundNode.EnumeratorInfoOpt); } [WorkItem(545489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545489")] [Fact] public void ForEachOnErrorTypesWithoutReferences() { var text = @" public class condGenClass<T> { } public class Test { static void Main() { Type[] types = {typeof(condGenClass<int>)}; foreach (Type t in types) { } } } "; var compilation = CreateEmptyCompilation(text); Assert.NotEmpty(compilation.GetDiagnostics()); } [WorkItem(545489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545489")] [Fact] public void ForEachWithoutCorlib_Array() { var text = @" public class Test { static void Main() { Test[] array = new Test[] { new Test() }; foreach (Test t in array) { } } } "; var compilation = CreateEmptyCompilation(text); Assert.NotEmpty(compilation.GetDiagnostics()); } [WorkItem(545489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545489")] [Fact] public void ForEachWithoutCorlib_String() { var text = @" public class Test { static void Main() { foreach (char ch in ""hello"") { } } } "; var compilation = CreateEmptyCompilation(text); Assert.NotEmpty(compilation.GetDiagnostics()); } [WorkItem(545186, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545186")] [Fact] public void TestForEachWithConditionalMethod() { string source = @" using System; using System.Collections; namespace ForEachTest { public class BaseEnumerator { public bool MoveNext() { Console.WriteLine(""BaseEnumerator::MoveNext()""); return false; } public int Current { get { Console.WriteLine(""BaseEnumerator::Current""); return 1; } } } public class BaseEnumeratorImpl : IEnumerator { public bool MoveNext() { Console.WriteLine(""BaseEnumeratorImpl::MoveNext()""); return false; } public Object Current { get { Console.WriteLine(""BaseEnumeratorImpl::Current""); return 1; } } public void Reset() { Console.WriteLine(""BaseEnumeratorImpl::Reset""); } } public class BasePattern { public BaseEnumerator GetEnumerator() { Console.WriteLine(""BasePattern::GetEnumerator()""); return new BaseEnumerator(); } } namespace ValidBaseTest { public class Derived5 : BasePattern, IEnumerable { IEnumerator IEnumerable.GetEnumerator() { Console.WriteLine(""<Interface> Derived5.GetEnumerator()""); return new BaseEnumeratorImpl(); } [System.Diagnostics.Conditional(""CONDITIONAL"")] new public void GetEnumerator() { Console.WriteLine(""ERROR: <Conditional Method not in scope> Derived5.GetEnumerator()""); } } } public class Logger { public static void Main() { foreach (int i in new ValidBaseTest.Derived5()) { } } } } "; // Without "CONDITIONAL" defined: Succeed string expectedOutput = @"<Interface> Derived5.GetEnumerator() BaseEnumeratorImpl::MoveNext()"; CompileAndVerify(source, expectedOutput: expectedOutput); // With "CONDITIONAL" defined: Fail // (a) Preprocessor symbol defined through command line parse options var options = new CSharpParseOptions(preprocessorSymbols: ImmutableArray.Create("CONDITIONAL"), documentationMode: DocumentationMode.None); CreateCompilation(source, parseOptions: options).VerifyDiagnostics( // (35,31): error CS0117: 'void' does not contain a definition for 'Current' // foreach (int i in new ValidBaseTest.Derived5()) { } Diagnostic(ErrorCode.ERR_NoSuchMember, "new ValidBaseTest.Derived5()").WithArguments("void", "Current").WithLocation(35, 31), // (35,31): error CS0202: foreach requires that the return type 'void' of 'ForEachTest.ValidBaseTest.Derived5.GetEnumerator()' must have a suitable public MoveNext method and public Current property // foreach (int i in new ValidBaseTest.Derived5()) { } Diagnostic(ErrorCode.ERR_BadGetEnumerator, "new ValidBaseTest.Derived5()").WithArguments("void", "ForEachTest.ValidBaseTest.Derived5.GetEnumerator()").WithLocation(35, 31)); // (b) Preprocessor symbol defined in source string condDefSource = "#define CONDITIONAL" + source; CreateCompilation(condDefSource).VerifyDiagnostics( // (35,31): error CS0117: 'void' does not contain a definition for 'Current' // foreach (int i in new ValidBaseTest.Derived5()) { } Diagnostic(ErrorCode.ERR_NoSuchMember, "new ValidBaseTest.Derived5()").WithArguments("void", "Current").WithLocation(35, 31), // (35,31): error CS0202: foreach requires that the return type 'void' of 'ForEachTest.ValidBaseTest.Derived5.GetEnumerator()' must have a suitable public MoveNext method and public Current property // foreach (int i in new ValidBaseTest.Derived5()) { } Diagnostic(ErrorCode.ERR_BadGetEnumerator, "new ValidBaseTest.Derived5()").WithArguments("void", "ForEachTest.ValidBaseTest.Derived5.GetEnumerator()").WithLocation(35, 31)); } [WorkItem(649809, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/649809")] [Fact] public void ArrayOfNullableOfError() { var source = @" class F { void Test() { E[] a1 = null; E?[] a2 = null; S<E>[] a3 = null; IEnumerable<E> e1 = null; IEnumerable<E?> e2 = null; IEnumerable<S<E>> e3 = null; foreach (E e in a1) { } foreach (E e in a2) { } foreach (E e in a2) { } foreach (E e in e1) { } foreach (E e in e2) { } foreach (E? e in a1) { } foreach (E? e in a2) { } // used to assert foreach (E? e in e1) { } foreach (E? e in e2) { } foreach (S<E> e in a3) { } foreach (S<E> e in e3) { } } } public struct S<T> { } "; Assert.NotEmpty(CreateCompilation(source).GetDiagnostics()); } [WorkItem(667616, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/667616")] [Fact] public void PortableLibraryStringForEach() { var source = @" class C { void Test(string s) { foreach (var c in s) { } } } "; var comp = CreateEmptyCompilation(source, new[] { MscorlibRefPortable }); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var loopSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var loopInfo = model.GetForEachStatementInfo(loopSyntax); Assert.False(loopInfo.IsAsynchronous); Assert.Equal<ISymbol>(comp.GetSpecialTypeMember(SpecialMember.System_Collections_IEnumerable__GetEnumerator).GetPublicSymbol(), loopInfo.GetEnumeratorMethod); Assert.Equal<ISymbol>(comp.GetSpecialTypeMember(SpecialMember.System_Collections_IEnumerator__Current).GetPublicSymbol(), loopInfo.CurrentProperty); Assert.Equal<ISymbol>(comp.GetSpecialTypeMember(SpecialMember.System_Collections_IEnumerator__MoveNext).GetPublicSymbol(), loopInfo.MoveNextMethod); Assert.Equal<ISymbol>(comp.GetSpecialTypeMember(SpecialMember.System_IDisposable__Dispose).GetPublicSymbol(), loopInfo.DisposeMethod); // The spec says that the element type is object. // Therefore, we should infer object for "var". Assert.Equal(SpecialType.System_Object, loopInfo.CurrentProperty.Type.SpecialType); // However, to match dev11, we actually infer "char" for "var". var typeInfo = model.GetTypeInfo(loopSyntax.Type); Assert.Equal(SpecialType.System_Char, typeInfo.Type.SpecialType); Assert.Equal(typeInfo.Type, typeInfo.ConvertedType); var conv = model.GetConversion(loopSyntax.Type); Assert.Equal(ConversionKind.Identity, conv.Kind); } [WorkItem(529956, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529956")] [Fact] public void CastArrayToIEnumerable() { var source = @" using System.Collections; class C { static void Main(string[] args) { foreach (C x in args) { } foreach (C x in (IEnumerable)args) { } } public static implicit operator C(string s) { return new C(); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var udc = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>(WellKnownMemberNames.ImplicitConversionName); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var loopSyntaxes = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().ToArray(); Assert.Equal(2, loopSyntaxes.Length); var loopInfo0 = model.GetForEachStatementInfo(loopSyntaxes[0]); Assert.Equal<ISymbol>(comp.GetSpecialTypeMember(SpecialMember.System_Collections_IEnumerable__GetEnumerator).GetPublicSymbol(), loopInfo0.GetEnumeratorMethod); Assert.Equal<ISymbol>(comp.GetSpecialTypeMember(SpecialMember.System_Collections_IEnumerator__Current).GetPublicSymbol(), loopInfo0.CurrentProperty); Assert.Equal<ISymbol>(comp.GetSpecialTypeMember(SpecialMember.System_Collections_IEnumerator__MoveNext).GetPublicSymbol(), loopInfo0.MoveNextMethod); Assert.Equal<ISymbol>(comp.GetSpecialTypeMember(SpecialMember.System_IDisposable__Dispose).GetPublicSymbol(), loopInfo0.DisposeMethod); Assert.Equal(SpecialType.System_String, loopInfo0.ElementType.SpecialType); Assert.Equal(udc, loopInfo0.ElementConversion.Method); Assert.Equal(ConversionKind.ExplicitReference, loopInfo0.CurrentConversion.Kind); var loopInfo1 = model.GetForEachStatementInfo(loopSyntaxes[1]); Assert.Equal(loopInfo0.GetEnumeratorMethod, loopInfo1.GetEnumeratorMethod); Assert.Equal(loopInfo0.CurrentProperty, loopInfo1.CurrentProperty); Assert.Equal(loopInfo0.MoveNextMethod, loopInfo1.MoveNextMethod); Assert.Equal(loopInfo0.DisposeMethod, loopInfo1.DisposeMethod); Assert.Equal(SpecialType.System_Object, loopInfo1.ElementType.SpecialType); // No longer string. Assert.Null(loopInfo1.ElementConversion.Method); // No longer using UDC. Assert.Equal(ConversionKind.Identity, loopInfo1.CurrentConversion.Kind); // Now identity. } [WorkItem(762179, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/762179")] [Fact] public void MissingObjectType() { var text = @" class C { void Goo(Enumerable e) { foreach (Element x in e) { } } } struct Enumerable { public Enumerator GetEnumerator() { return new Enumerator(); } } struct Enumerator { public Element Current { get { return null; } } public bool MoveNext() { return false; } } class Element { } "; var comp = CreateEmptyCompilation(text); comp.GetDiagnostics(); } [WorkItem(798000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/798000")] [WorkItem(39948, "https://github.com/dotnet/roslyn/issues/39948")] [Fact] public void MissingNullableValue() { var text = @" namespace System { public class Object { } public class ValueType {} public struct Void { } public struct Nullable<T> { } public struct Boolean { } } namespace System.Collections.Generic { public interface IEnumerable<T> { IEnumerator<T> GetEnumerator(); } public interface IEnumerator<T> { T Current { get; } bool MoveNext(); } } class C { void Goo(System.Collections.Generic.IEnumerable<C>? e) { foreach (var c in e) { } } } "; var comp = CreateEmptyCompilation(text); comp.VerifyDiagnostics( // (28,55): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // void Goo(System.Collections.Generic.IEnumerable<C>? e) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(28, 55) ); comp.VerifyEmitDiagnostics( // warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options. Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Byte' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1), // (28,55): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // void Goo(System.Collections.Generic.IEnumerable<C>? e) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(28, 55), // The following error is unexpected - https://github.com/dotnet/roslyn/issues/39948 // (30,9): error CS0656: Missing compiler required member 'System.IDisposable.Dispose' // foreach (var c in e) { } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "foreach (var c in e) { }").WithArguments("System.IDisposable", "Dispose").WithLocation(30, 9) ); } [WorkItem(798000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/798000")] [Fact] public void MissingNullableValue_CSharp7() { var text = @" namespace System { public class Object { } public class ValueType {} public struct Void { } public struct Nullable<T> { } public struct Boolean { } } namespace System.Collections.Generic { public interface IEnumerable<T> { IEnumerator<T> GetEnumerator(); } public interface IEnumerator<T> { T Current { get; } bool MoveNext(); } } class C { void Goo(System.Collections.Generic.IEnumerable<C>? e) { foreach (var c in e) { } } } "; var expected = new[] { // (28,55): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater. // void Goo(System.Collections.Generic.IEnumerable<C>? e) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "?").WithArguments("nullable reference types", "8.0").WithLocation(28, 55) }; var comp = CreateEmptyCompilation(text, parseOptions: TestOptions.Regular7_3, skipUsesIsNullable: true); comp.VerifyDiagnostics(expected); comp = CreateEmptyCompilation(text, skipUsesIsNullable: true); comp.VerifyDiagnostics( // (28,55): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // void Goo(System.Collections.Generic.IEnumerable<C>? e) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(28, 55) ); } [WorkItem(798000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/798000")] [Fact] public void MissingIEnumerableTGetEnumerator() { var text = @" namespace System { public class Object { } public class ValueType {} public struct Void { } public struct Boolean { } } namespace System.Collections.Generic { public interface IEnumerable<T> { } } public class Enumerable<T> : System.Collections.Generic.IEnumerable<T> { } class C { void Goo(System.Collections.Generic.IEnumerable<C> e1, Enumerable<C> e2) { foreach (var c in e1) { } // Pattern foreach (var c in e2) { } // Interface } } "; var comp = CreateEmptyCompilation(text); comp.VerifyDiagnostics( // For pattern: // (22,27): error CS1579: foreach statement cannot operate on variables of type 'System.Collections.Generic.IEnumerable<C>' because 'System.Collections.Generic.IEnumerable<C>' does not contain a public definition for 'GetEnumerator' // foreach (var c in e1) { } Diagnostic(ErrorCode.ERR_ForEachMissingMember, "e1").WithArguments("System.Collections.Generic.IEnumerable<C>", "GetEnumerator"), // For interface: // (23,27): error CS0656: Missing compiler required member 'System.Collections.Generic.IEnumerable`1.GetEnumerator' // foreach (var c in e2) { } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "e2").WithArguments("System.Collections.Generic.IEnumerable`1", "GetEnumerator"), // (23,27): error CS0656: Missing compiler required member 'System.Collections.IEnumerator.MoveNext' // foreach (var c in e2) { } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "e2").WithArguments("System.Collections.IEnumerator", "MoveNext")); } [WorkItem(798000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/798000")] [Fact] public void MissingIEnumeratorTMoveNext() { var text = @" namespace System { public class Object { } public class ValueType {} public struct Void { } public struct Boolean { } } namespace System.Collections.Generic { public interface IEnumerable<T> { IEnumerator<T> GetEnumerator(); } public interface IEnumerator<T> { T Current { get; } } } public class Enumerable<T> : System.Collections.Generic.IEnumerable<T> { System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator() { return null; } } class C { void Goo(System.Collections.Generic.IEnumerable<C> e1, Enumerable<C> e2) { foreach (var c in e1) { } // Pattern foreach (var c in e2) { } // Interface } } "; var comp = CreateEmptyCompilation(text); comp.VerifyDiagnostics( // For pattern: // (37,27): error CS0117: 'System.Collections.Generic.IEnumerator<C>' does not contain a definition for 'MoveNext' // foreach (var c in e1) { } // Pattern Diagnostic(ErrorCode.ERR_NoSuchMember, "e1").WithArguments("System.Collections.Generic.IEnumerator<C>", "MoveNext"), // For interface: // (37,27): error CS0202: foreach requires that the return type 'System.Collections.Generic.IEnumerator<C>' of 'System.Collections.Generic.IEnumerable<C>.GetEnumerator()' must have a suitable public MoveNext method and public Current property // foreach (var c in e1) { } // Pattern Diagnostic(ErrorCode.ERR_BadGetEnumerator, "e1").WithArguments("System.Collections.Generic.IEnumerator<C>", "System.Collections.Generic.IEnumerable<C>.GetEnumerator()"), // (38,27): error CS0656: Missing compiler required member 'System.Collections.IEnumerator.MoveNext' // foreach (var c in e2) { } // Interface Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "e2").WithArguments("System.Collections.IEnumerator", "MoveNext")); } [WorkItem(798000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/798000")] [Fact] public void MissingIEnumeratorTCurrent() { var text = @" namespace System { public class Object { } public class ValueType {} public struct Void { } public struct Boolean { } } namespace System.Collections { public interface IEnumerator { bool MoveNext(); } } namespace System.Collections.Generic { public interface IEnumerable<T> { IEnumerator<T> GetEnumerator(); } public interface IEnumerator<T> : IEnumerator { //T Current { get; } } } public class Enumerable<T> : System.Collections.Generic.IEnumerable<T> { System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator() { return null; } } class C { void Goo(System.Collections.Generic.IEnumerable<C> e1, Enumerable<C> e2) { foreach (var c in e1) { } // Pattern foreach (var c in e2) { } // Interface } } "; var comp = CreateEmptyCompilation(text); comp.VerifyDiagnostics( // For pattern: // (44,27): error CS0117: 'System.Collections.Generic.IEnumerator<C>' does not contain a definition for 'Current' // foreach (var c in e1) { } // Pattern Diagnostic(ErrorCode.ERR_NoSuchMember, "e1").WithArguments("System.Collections.Generic.IEnumerator<C>", "Current"), // (44,27): error CS0202: foreach requires that the return type 'System.Collections.Generic.IEnumerator<C>' of 'System.Collections.Generic.IEnumerable<C>.GetEnumerator()' must have a suitable public MoveNext method and public Current property // foreach (var c in e1) { } // Pattern Diagnostic(ErrorCode.ERR_BadGetEnumerator, "e1").WithArguments("System.Collections.Generic.IEnumerator<C>", "System.Collections.Generic.IEnumerable<C>.GetEnumerator()"), // For interface: // (45,27): error CS0656: Missing compiler required member 'System.Collections.Generic.IEnumerator`1.get_Current' // foreach (var c in e2) { } // Interface Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "e2").WithArguments("System.Collections.Generic.IEnumerator`1", "get_Current")); } [WorkItem(798000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/798000")] [Fact] public void MissingIEnumeratorTCurrentGetter() { var text = @" namespace System { public class Object { } public class ValueType {} public struct Void { } public struct Boolean { } } namespace System.Collections { public interface IEnumerator { bool MoveNext(); } } namespace System.Collections.Generic { public interface IEnumerable<T> { IEnumerator<T> GetEnumerator(); } public interface IEnumerator<T> : IEnumerator { T Current { /* get; */ set; } } } public class Enumerable<T> : System.Collections.Generic.IEnumerable<T> { System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator() { return null; } } class C { void Goo(System.Collections.Generic.IEnumerable<C> e1, Enumerable<C> e2) { foreach (var c in e1) { } // Pattern foreach (var c in e2) { } // Interface } } "; var comp = CreateEmptyCompilation(text); comp.VerifyDiagnostics( // For pattern: // (44,27): error CS0202: foreach requires that the return type 'System.Collections.Generic.IEnumerator<C>' of 'System.Collections.Generic.IEnumerable<C>.GetEnumerator()' must have a suitable public MoveNext method and public Current property // foreach (var c in e1) { } // Pattern Diagnostic(ErrorCode.ERR_BadGetEnumerator, "e1").WithArguments("System.Collections.Generic.IEnumerator<C>", "System.Collections.Generic.IEnumerable<C>.GetEnumerator()"), // For interface: // (45,27): error CS0656: Missing compiler required member 'System.Collections.Generic.IEnumerator`1.get_Current' // foreach (var c in e2) { } // Interface Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "e2").WithArguments("System.Collections.Generic.IEnumerator`1", "get_Current")); } [WorkItem(798000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/798000")] [Fact] public void MissingIEnumerableGetEnumerator() { var text = @" namespace System { public class Object { } public class ValueType {} public struct Void { } public struct Boolean { } } namespace System.Collections { public interface IEnumerable { } } public class Enumerable : System.Collections.IEnumerable { } class C { void Goo(System.Collections.IEnumerable e1, Enumerable e2) { foreach (var c in e1) { } // Pattern foreach (var c in e2) { } // Interface } } "; var comp = CreateEmptyCompilation(text); comp.VerifyDiagnostics( // For pattern: // (22,27): error CS1579: foreach statement cannot operate on variables of type 'System.Collections.IEnumerable' because 'System.Collections.IEnumerable' does not contain a public definition for 'GetEnumerator' // foreach (var c in e1) { } Diagnostic(ErrorCode.ERR_ForEachMissingMember, "e1").WithArguments("System.Collections.IEnumerable", "GetEnumerator"), // For interface: // (23,27): error CS0656: Missing compiler required member 'System.Collections.IEnumerable.GetEnumerator' // foreach (var c in e2) { } // Interface Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "e2").WithArguments("System.Collections.IEnumerable", "GetEnumerator"), // (23,27): error CS0656: Missing compiler required member 'System.Collections.IEnumerator.get_Current' // foreach (var c in e2) { } // Interface Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "e2").WithArguments("System.Collections.IEnumerator", "get_Current"), // (23,27): error CS0656: Missing compiler required member 'System.Collections.IEnumerator.MoveNext' // foreach (var c in e2) { } // Interface Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "e2").WithArguments("System.Collections.IEnumerator", "MoveNext")); } [WorkItem(798000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/798000")] [Fact] public void MissingIEnumeratorMoveNext() { var text = @" namespace System { public class Object { } public class ValueType {} public struct Void { } public struct Boolean { } } namespace System.Collections { public interface IEnumerable { IEnumerator GetEnumerator(); } public interface IEnumerator { object Current { get; } } } public class Enumerable : System.Collections.IEnumerable { System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return null; } } class C { void Goo(System.Collections.IEnumerable e1, Enumerable e2) { foreach (var c in e1) { } // Pattern foreach (var c in e2) { } // Interface } } "; var comp = CreateEmptyCompilation(text); comp.VerifyDiagnostics( // For pattern: // (37,27): error CS0117: 'System.Collections.IEnumerator' does not contain a definition for 'MoveNext' // foreach (var c in e1) { } // Pattern Diagnostic(ErrorCode.ERR_NoSuchMember, "e1").WithArguments("System.Collections.IEnumerator", "MoveNext"), // For interface: // (37,27): error CS0202: foreach requires that the return type 'System.Collections.IEnumerator' of 'System.Collections.IEnumerable.GetEnumerator()' must have a suitable public MoveNext method and public Current property // foreach (var c in e1) { } // Pattern Diagnostic(ErrorCode.ERR_BadGetEnumerator, "e1").WithArguments("System.Collections.IEnumerator", "System.Collections.IEnumerable.GetEnumerator()"), // (38,27): error CS0656: Missing compiler required member 'System.Collections.IEnumerator.MoveNext' // foreach (var c in e2) { } // Interface Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "e2").WithArguments("System.Collections.IEnumerator", "MoveNext")); } [WorkItem(798000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/798000")] [Fact] public void MissingIEnumeratorCurrent() { var text = @" namespace System { public class Object { } public class ValueType {} public struct Void { } public struct Boolean { } } namespace System.Collections { public interface IEnumerable { IEnumerator GetEnumerator(); } public interface IEnumerator { bool MoveNext(); //object Current { get; } } } public class Enumerable : System.Collections.IEnumerable { System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return null; } } class C { void Goo(System.Collections.IEnumerable e1, Enumerable e2) { foreach (var c in e1) { } // Pattern foreach (var c in e2) { } // Interface } } "; var comp = CreateEmptyCompilation(text); comp.VerifyDiagnostics( // For pattern: // (44,27): error CS0117: 'System.Collections.IEnumerator' does not contain a definition for 'Current' // foreach (var c in e1) { } // Pattern Diagnostic(ErrorCode.ERR_NoSuchMember, "e1").WithArguments("System.Collections.IEnumerator", "Current"), // (44,27): error CS0202: foreach requires that the return type 'System.Collections.IEnumerator' of 'System.Collections.IEnumerable.GetEnumerator()' must have a suitable public MoveNext method and public Current property // foreach (var c in e1) { } // Pattern Diagnostic(ErrorCode.ERR_BadGetEnumerator, "e1").WithArguments("System.Collections.IEnumerator", "System.Collections.IEnumerable.GetEnumerator()"), // For interface: // (45,27): error CS0656: Missing compiler required member 'System.Collections.IEnumerator.get_Current' // foreach (var c in e2) { } // Interface Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "e2").WithArguments("System.Collections.IEnumerator", "get_Current")); } [WorkItem(798000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/798000")] [Fact] public void MissingIEnumeratorCurrentGetter() { var text = @" namespace System { public class Object { } public class ValueType {} public struct Void { } public struct Boolean { } } namespace System.Collections { public interface IEnumerable { IEnumerator GetEnumerator(); } public interface IEnumerator { bool MoveNext(); object Current { /* get; */ set; } } } public class Enumerable : System.Collections.IEnumerable { System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return null; } } class C { void Goo(System.Collections.IEnumerable e1, Enumerable e2) { foreach (var c in e1) { } // Pattern foreach (var c in e2) { } // Interface } } "; var comp = CreateEmptyCompilation(text); comp.VerifyDiagnostics( // For pattern: // (44,27): error CS0202: foreach requires that the return type 'System.Collections.IEnumerator' of 'System.Collections.IEnumerable.GetEnumerator()' must have a suitable public MoveNext method and public Current property // foreach (var c in e1) { } // Pattern Diagnostic(ErrorCode.ERR_BadGetEnumerator, "e1").WithArguments("System.Collections.IEnumerator", "System.Collections.IEnumerable.GetEnumerator()"), // For interface: // (45,27): error CS0656: Missing compiler required member 'System.Collections.IEnumerator.get_Current' // foreach (var c in e2) { } // Interface Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "e2").WithArguments("System.Collections.IEnumerator", "get_Current")); } [WorkItem(530381, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530381")] [Fact] public void BadCollectionCascadingErrors() { var source = @" class Program { static void Main() { foreach(var x in Goo) { } } } "; CreateCompilation(source).VerifyDiagnostics( // (6,26): error CS0103: The name 'Goo' does not exist in the current context // foreach(var x in Goo) { } Diagnostic(ErrorCode.ERR_NameNotInContext, "Goo").WithArguments("Goo").WithLocation(6, 26)); } [WorkItem(847507, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/847507")] [Fact] public void InferIterationVariableTypeWithErrors() { var source = @" class Program { static void Main() { foreach(var x in new string[1]) { } } } namespace System { public class Object { } public class String : Object { } } "; var comp = CreateEmptyCompilation(source); // Lots of errors, since corlib is missing. var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var localSymbol = model.GetDeclaredSymbol(foreachSyntax); // Code Path 1: SourceLocalSymbol.Type. var localSymbolType = localSymbol.Type; Assert.Equal(SpecialType.System_String, localSymbolType.SpecialType); Assert.NotEqual(TypeKind.Error, localSymbolType.TypeKind); // Code Path 2: SemanticModel. var varSyntax = foreachSyntax.Type; var info = model.GetSymbolInfo(varSyntax); // Used to assert. Assert.Equal(localSymbolType, info.Symbol); } [WorkItem(667275, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/667275")] [Fact] public void Repro667275() { // This is not the simplest repro, but it is the one from the bug. var source = @" using System.Collections.Generic; class myClass<T> { public static implicit operator T(myClass<T> m) { return default(T); } } class Test { static void Main() { var myObj = new myClass<List<string>>(); foreach (var x in myObj) { } } } "; CreateCompilation(source).VerifyDiagnostics( // (14,27): error CS1579: foreach statement cannot operate on variables of type 'myClass<System.Collections.Generic.List<string>>' because 'myClass<System.Collections.Generic.List<string>>' does not contain a public definition for 'GetEnumerator' // foreach (var x in myObj) { } Diagnostic(ErrorCode.ERR_ForEachMissingMember, "myObj").WithArguments("myClass<System.Collections.Generic.List<string>>", "GetEnumerator").WithLocation(14, 27)); } [WorkItem(667275, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/667275")] [Fact] public void Repro667275_Simplified() { // No generics, no foreach. var source = @" using System.Collections; class Dummy { public static implicit operator MyEnumerable(Dummy d) { return null; } } public class MyEnumerable : IEnumerable { IEnumerator IEnumerable.GetEnumerator() { throw new System.NotImplementedException(); } } class Test { static void Main() { Dummy d = new Dummy(); MyEnumerable m = d; // succeeds IEnumerable i = d; // fails } } "; CreateCompilation(source).VerifyDiagnostics( // (27,25): error CS0266: Cannot implicitly convert type 'Dummy' to 'System.Collections.IEnumerable'. An explicit conversion exists (are you missing a cast?) // IEnumerable i = d; // fails Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "d").WithArguments("Dummy", "System.Collections.IEnumerable").WithLocation(27, 25)); } [WorkItem(963197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/963197")] [Fact] public void Repro963197() { var source = @"using System; class Program { public static string B = ""B""; public static string C = ""C""; static void Main(string[] args) { foreach (var a in new { B, C }) { Console.WriteLine(a); } } }"; CreateCompilation(source).VerifyDiagnostics( // (9,27): error CS1579: foreach statement cannot operate on variables of type '<anonymous type: string B, string C>' because '<anonymous type: string B, string C>' does not contain a public definition for 'GetEnumerator' // foreach (var a in new { B, C }) Diagnostic(ErrorCode.ERR_ForEachMissingMember, "new { B, C }").WithArguments("<anonymous type: string B, string C>", "GetEnumerator").WithLocation(9, 27) ); } [WorkItem(11387, "https://github.com/dotnet/roslyn/issues/11387")] [Fact] public void StringNotIEnumerable() { var source1 = @"namespace System { public class Object { } public struct Void { } public class ValueType { } public struct Boolean { } public struct Int32 { } public struct Char { } public class String { public int Length => 2; [System.Runtime.CompilerServices.IndexerName(""Chars"")] public char this[int i] => 'a'; } public interface IDisposable { void Dispose(); } public abstract class Attribute { protected Attribute() { } } } namespace System.Runtime.CompilerServices { using System; public sealed class IndexerNameAttribute: Attribute { public IndexerNameAttribute(String indexerName) {} } } namespace System.Reflection { using System; public sealed class DefaultMemberAttribute : Attribute { public DefaultMemberAttribute(String memberName) {} } } namespace System.Collections { public interface IEnumerable { IEnumerator GetEnumerator(); } public interface IEnumerator { object Current { get; } bool MoveNext(); } }"; var compilation1 = CreateEmptyCompilation(source1, assemblyName: GetUniqueName()); var reference1 = MetadataReference.CreateFromStream(compilation1.EmitToStream()); var text = @"class C { static void M(string s) { foreach (var c in s) { // comment } } }"; var comp = CreateEmptyCompilation(text, new[] { reference1 }); CompileAndVerify(comp, verify: Verification.Fails). VerifyIL("C.M", @" { // Code size 28 (0x1c) .maxstack 2 .locals init (string V_0, int V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldc.i4.0 IL_0003: stloc.1 IL_0004: br.s IL_0012 IL_0006: ldloc.0 IL_0007: ldloc.1 IL_0008: callvirt ""char string.this[int].get"" IL_000d: pop IL_000e: ldloc.1 IL_000f: ldc.i4.1 IL_0010: add IL_0011: stloc.1 IL_0012: ldloc.1 IL_0013: ldloc.0 IL_0014: callvirt ""int string.Length.get"" IL_0019: blt.s IL_0006 IL_001b: ret } "); var boundNode = GetBoundForEachStatement(text); ForEachEnumeratorInfo info = boundNode.EnumeratorInfoOpt; Assert.NotNull(info); Assert.Equal(SpecialType.System_String, info.CollectionType.SpecialType); Assert.Equal(SpecialType.System_Char, info.ElementTypeWithAnnotations.SpecialType); Assert.Equal("System.CharEnumerator System.String.GetEnumerator()", info.GetEnumeratorInfo.Method.ToTestDisplayString()); Assert.Empty(info.GetEnumeratorInfo.Arguments); Assert.Equal("System.Char System.CharEnumerator.Current.get", info.CurrentPropertyGetter.ToTestDisplayString()); Assert.Equal("System.Boolean System.CharEnumerator.MoveNext()", info.MoveNextInfo.Method.ToTestDisplayString()); Assert.Empty(info.MoveNextInfo.Arguments); Assert.True(info.NeedsDisposal); Assert.Equal(ConversionKind.Identity, info.CollectionConversion.Kind); Assert.Equal(ConversionKind.Identity, info.CurrentConversion.Kind); Assert.Equal(ConversionKind.ImplicitReference, info.EnumeratorConversion.Kind); Assert.Equal(ConversionKind.Identity, boundNode.ElementConversion.Kind); Assert.Equal(SpecialType.System_Char, boundNode.IterationVariables.Single().Type.SpecialType); } [Fact] public void TestPatternDisposeRefStruct() { var text = @" class C { static void Main() { foreach (var x in new Enumerable1()) { System.Console.WriteLine(x); } } } class Enumerable1 { public DisposableEnumerator GetEnumerator() { return new DisposableEnumerator(); } } ref struct DisposableEnumerator { int x; public int Current { get { return x; } } public bool MoveNext() { return ++x < 4; } public void Dispose() { } }"; var boundNode = GetBoundForEachStatement(text); var enumeratorInfo = boundNode.EnumeratorInfoOpt; Assert.Equal("void DisposableEnumerator.Dispose()", enumeratorInfo.PatternDisposeInfo.Method.ToTestDisplayString()); Assert.Empty(enumeratorInfo.PatternDisposeInfo.Arguments); } [Fact] public void TestPatternDisposeRefStruct_7_3() { var text = @" class C { static void Main() { foreach (var x in new Enumerable1()) { System.Console.WriteLine(x); } } } class Enumerable1 { public DisposableEnumerator GetEnumerator() { return new DisposableEnumerator(); } } ref struct DisposableEnumerator { int x; public int Current { get { return x; } } public bool MoveNext() { return ++x < 4; } public void Dispose() { } }"; var boundNode = GetBoundForEachStatement(text, TestOptions.Regular7_3); var enumeratorInfo = boundNode.EnumeratorInfoOpt; Assert.Null(enumeratorInfo.PatternDisposeInfo); } [Fact] public void TestExtensionGetEnumerator() { var text = @" using System; public class C { public static void Main() { foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public bool MoveNext() => Current++ != 3; } } public static class Extensions { public static C.Enumerator GetEnumerator(this C self) => new C.Enumerator(); }"; var boundNode = GetBoundForEachStatement(text, options: TestOptions.Regular9); ForEachEnumeratorInfo info = boundNode.EnumeratorInfoOpt; Assert.NotNull(info); Assert.Equal("C", info.CollectionType.ToTestDisplayString()); Assert.Equal(SpecialType.System_Int32, info.ElementTypeWithAnnotations.SpecialType); Assert.Equal("C.Enumerator Extensions.GetEnumerator(this C self)", info.GetEnumeratorInfo.Method.ToTestDisplayString()); Assert.Equal("C", info.GetEnumeratorInfo.Arguments.Single().Type.ToTestDisplayString()); Assert.Equal("System.Int32 C.Enumerator.Current.get", info.CurrentPropertyGetter.ToTestDisplayString()); Assert.Equal("System.Boolean C.Enumerator.MoveNext()", info.MoveNextInfo.Method.ToTestDisplayString()); Assert.Empty(info.MoveNextInfo.Arguments); Assert.False(info.NeedsDisposal); Assert.Equal(ConversionKind.Identity, info.CollectionConversion.Kind); Assert.Equal(ConversionKind.Identity, info.CurrentConversion.Kind); Assert.Equal(ConversionKind.ImplicitReference, info.EnumeratorConversion.Kind); Assert.Equal(ConversionKind.Identity, boundNode.ElementConversion.Kind); Assert.Equal("System.Int32 i", boundNode.IterationVariables.Single().ToTestDisplayString()); Assert.Equal("C", boundNode.Expression.Type.ToDisplayString()); } private static BoundForEachStatement GetBoundForEachStatement(string text, CSharpParseOptions options = null, params DiagnosticDescription[] diagnostics) { var tree = Parse(text, options: options); var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { tree }); comp.VerifyDiagnostics(diagnostics); var syntaxNode = (CommonForEachStatementSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.ForEachStatement).AsNode() ?? (CommonForEachStatementSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.ForEachVariableStatement).AsNode(); var treeModel = (SyntaxTreeSemanticModel)comp.GetSemanticModel(tree); var memberModel = treeModel.GetMemberModel(syntaxNode); BoundForEachStatement boundNode = (BoundForEachStatement)memberModel.GetUpperBoundNode(syntaxNode); // Make sure that the bound node info is exposed correctly in the API ForEachEnumeratorInfo enumeratorInfo = boundNode.EnumeratorInfoOpt; ForEachStatementInfo statementInfo = treeModel.GetForEachStatementInfo(syntaxNode); if (enumeratorInfo == null) { Assert.Equal(default(ForEachStatementInfo), statementInfo); } else { Assert.Equal(enumeratorInfo.GetEnumeratorInfo.Method.GetPublicSymbol(), statementInfo.GetEnumeratorMethod); Assert.Equal(enumeratorInfo.CurrentPropertyGetter.GetPublicSymbol(), statementInfo.CurrentProperty.GetMethod); Assert.Equal(enumeratorInfo.MoveNextInfo.Method.GetPublicSymbol(), statementInfo.MoveNextMethod); if (enumeratorInfo.NeedsDisposal) { if (enumeratorInfo.PatternDisposeInfo is object) { Assert.Equal(enumeratorInfo.PatternDisposeInfo.Method.GetPublicSymbol(), statementInfo.DisposeMethod); } else if (enumeratorInfo.IsAsync) { Assert.Equal("System.ValueTask System.IAsyncDisposable.DisposeAsync()", statementInfo.DisposeMethod.ToTestDisplayString()); } else { Assert.Equal("void System.IDisposable.Dispose()", statementInfo.DisposeMethod.ToTestDisplayString()); } } else { Assert.Null(statementInfo.DisposeMethod); } Assert.Equal(enumeratorInfo.ElementType.GetPublicSymbol(), statementInfo.ElementType); Assert.Equal(boundNode.ElementConversion, statementInfo.ElementConversion); Assert.Equal(enumeratorInfo.CurrentConversion, statementInfo.CurrentConversion); } return boundNode; } [WorkItem(1100741, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1100741")] [Fact] public void Bug1100741() { var source = @" namespace ImmutableObjectGraph { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using IdentityFieldType = System.UInt32; public static class RecursiveTypeExtensions { /// <summary>Gets the recursive parent of the specified value, or <c>null</c> if none could be found.</summary> internal ParentedRecursiveType<<#= templateType.RecursiveParent.TypeName #>, <#= templateType.RecursiveTypeFromFamily.TypeName #>> GetParentedNode(<#= templateType.RequiredIdentityField.TypeName #> identity) { if (this.Identity == identity) { return new ParentedRecursiveType<<#= templateType.RecursiveParent.TypeName #>, <#= templateType.RecursiveTypeFromFamily.TypeName #>>(this, null); } if (this.LookupTable != null) { System.Collections.Generic.KeyValuePair<<#= templateType.RecursiveType.TypeName #>, <#= templateType.RequiredIdentityField.TypeName #>> lookupValue; if (this.LookupTable.TryGetValue(identity, out lookupValue)) { var parentIdentity = lookupValue.Value; return new ParentedRecursiveType<<#= templateType.RecursiveParent.TypeName #>, <#= templateType.RecursiveTypeFromFamily.TypeName #>>(this.LookupTable[identity].Key, (<#= templateType.RecursiveParent.TypeName #>)this.Find(parentIdentity)); } } else { // No lookup table means we have to aggressively search each child. foreach (var child in this.Children) { if (child.Identity.Equals(identity)) { return new ParentedRecursiveType<<#= templateType.RecursiveParent.TypeName #>, <#= templateType.RecursiveTypeFromFamily.TypeName #>>(child, this); } var recursiveChild = child as <#= templateType.RecursiveParent.TypeName #>; if (recursiveChild != null) { var childResult = recursiveChild.GetParentedNode(identity); if (childResult.Value != null) { return childResult; } } } } return default(ParentedRecursiveType<<#= templateType.RecursiveParent.TypeName #>, <#= templateType.RecursiveTypeFromFamily.TypeName #>>); } } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().Where(n => n.Kind() == SyntaxKind.ForEachStatement).OfType<ForEachStatementSyntax>().Single(); var model = compilation.GetSemanticModel(tree); Assert.Null(model.GetDeclaredSymbol(node)); } [Fact, WorkItem(1733, "https://github.com/dotnet/roslyn/issues/1733")] public void MissingBaseType() { var source1 = @" namespace System { public class Object { } public class ValueType {} public struct Void { } public struct Boolean { } public struct Int32 { } } "; var comp1 = CreateEmptyCompilation(source1, options: TestOptions.DebugDll, assemblyName: "MissingBaseType1"); comp1.VerifyDiagnostics(); var source2 = @" public class Enumerable { public Enumerator GetEnumerator() { return default(Enumerator); } } public struct Enumerator { public int Current { get { return 0; } } public bool MoveNext() { return false; } }"; var comp2 = CreateEmptyCompilation(source2, new[] { comp1.ToMetadataReference() }, options: TestOptions.DebugDll); comp2.VerifyDiagnostics(); var source3 = @" namespace System { public class Object { } public class ValueType {} public struct Void { } public struct Boolean { } public struct Int32 { } } "; var comp3 = CreateEmptyCompilation(source3, options: TestOptions.DebugDll, assemblyName: "MissingBaseType2"); comp3.VerifyDiagnostics(); var source4 = @" class Program { static void Main() { foreach (var x in new Enumerable()) { } } }"; var comp4 = CreateEmptyCompilation(source4, new[] { comp2.ToMetadataReference(), comp3.ToMetadataReference() }); comp4.VerifyDiagnostics( // (6,9): error CS0012: The type 'ValueType' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingBaseType1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // foreach (var x in new Enumerable()) Diagnostic(ErrorCode.ERR_NoTypeDef, @"foreach (var x in new Enumerable()) { }").WithArguments("System.ValueType", "MissingBaseType1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 9) ); } [Fact] [WorkItem(26585, "https://github.com/dotnet/roslyn/issues/26585")] public void ForEachIteratorWithCurrentRefKind_Async_Ref() { CreateCompilation(@" using System.Threading.Tasks; class E { public class Enumerator { public ref int Current => throw null; public bool MoveNext() => throw null; } public Enumerator GetEnumerator() => new Enumerator(); } class C { public async static Task Test() { await Task.CompletedTask; foreach (ref int x in new E()) { System.Console.Write(x); } } }").VerifyDiagnostics( // (20,26): error CS8177: Async methods cannot have by-reference locals // foreach (ref int x in new E()) Diagnostic(ErrorCode.ERR_BadAsyncLocalType, "x").WithLocation(20, 26)); } [Fact] [WorkItem(26585, "https://github.com/dotnet/roslyn/issues/26585")] public void ForEachIteratorWithCurrentRefKind_Async_RefReadonly() { CreateCompilation(@" using System.Threading.Tasks; class E { public class Enumerator { public ref readonly int Current => throw null; public bool MoveNext() => throw null; } public Enumerator GetEnumerator() => new Enumerator(); } class C { public async static Task Test() { await Task.CompletedTask; foreach (ref readonly int x in new E()) { System.Console.Write(x); } } }").VerifyDiagnostics( // (20,35): error CS8177: Async methods cannot have by-reference locals // foreach (ref readonly int x in new E()) Diagnostic(ErrorCode.ERR_BadAsyncLocalType, "x").WithLocation(20, 35)); } [Fact] [WorkItem(26585, "https://github.com/dotnet/roslyn/issues/26585")] public void ForEachIteratorWithCurrentRefKind_Iterator_Ref() { CreateCompilation(@" using System.Collections.Generic; class E { public class Enumerator { public ref int Current => throw null; public bool MoveNext() => throw null; } public Enumerator GetEnumerator() => new Enumerator(); } class C { public static IEnumerable<int> Test() { foreach (ref int x in new E()) { yield return x; } } }").VerifyDiagnostics( // (18,26): error CS8176: Iterators cannot have by-reference locals // foreach (ref int x in new E()) Diagnostic(ErrorCode.ERR_BadIteratorLocalType, "x").WithLocation(18, 26)); } [Fact] [WorkItem(26585, "https://github.com/dotnet/roslyn/issues/26585")] public void ForEachIteratorWithCurrentRefKind_Iterator_RefReadonly() { CreateCompilation(@" using System.Collections.Generic; class E { public class Enumerator { public ref readonly int Current => throw null; public bool MoveNext() => throw null; } public Enumerator GetEnumerator() => new Enumerator(); } class C { public static IEnumerable<int> Test() { foreach (ref readonly int x in new E()) { yield return x; } } }").VerifyDiagnostics( // (18,35): error CS8176: Iterators cannot have by-reference locals // foreach (ref readonly int x in new E()) Diagnostic(ErrorCode.ERR_BadIteratorLocalType, "x").WithLocation(18, 35)); } [Fact] [WorkItem(30016, "https://github.com/dotnet/roslyn/issues/30016")] public void ForEachIteratorWithCurrentRefKind_DontPassFieldByValue() { var source = @" using System; struct S1 { public int A; } class C { public static void Main() { Span<S1> items = new Span<S1>(new S1[1]); foreach (ref var t in items) t.A++; Console.WriteLine(items[0].A); } }"; var comp = CreateCompilationWithMscorlibAndSpan(source, options: TestOptions.ReleaseDebugExe).VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "1"); } [WorkItem(32334, "https://github.com/dotnet/roslyn/issues/32334")] [Fact] public void SuppressForEachMissingMemberErrorOnErrorType() { CreateCompilation(@" using System; using System.Collections.Generic; class C { void Goo() { var nonsense = Nonsense; //Should not have error foreach(var item in nonsense) {} var nonsense2 = new Nonsense(); //Should not have error foreach(var item in nonsense2) {} var lazyNonsense = default(Lazy<Nonsense>); //Should have error foreach(var item in lazyNonsense) {} var listNonsense = new List<Nonsense>(); //Should not have error foreach(var item in listNonsense) {} var nonsenseArray = new Nonsense[0]; //Should not have error foreach(var item in nonsenseArray) {} var stringNonsense = new String.Nonsense(); //Should not have error foreach(var item in stringNonsense) {} var nonsenseString = new Nonsense.String(); //Should not have error foreach(var item in nonsenseString) {} Nonsense? nullableNonsense = default; //Should have error foreach(var item in nullableNonsense) {} var nonsenseTuple = (new Nonsense(), 42); //Should have error foreach(var item in nonsenseTuple) {} } } ").VerifyDiagnostics( // (9,24): error CS0103: The name 'Nonsense' does not exist in the current context // var nonsense = Nonsense; Diagnostic(ErrorCode.ERR_NameNotInContext, "Nonsense").WithArguments("Nonsense").WithLocation(9, 24), // (13,29): error CS0246: The type or namespace name 'Nonsense' could not be found (are you missing a using directive or an assembly reference?) // var nonsense2 = new Nonsense(); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Nonsense").WithArguments("Nonsense").WithLocation(13, 29), // (17,41): error CS0246: The type or namespace name 'Nonsense' could not be found (are you missing a using directive or an assembly reference?) // var lazyNonsense = default(Lazy<Nonsense>); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Nonsense").WithArguments("Nonsense").WithLocation(17, 41), // (19,29): error CS1579: foreach statement cannot operate on variables of type 'Lazy<Nonsense>' because 'Lazy<Nonsense>' does not contain a public instance or extension definition for 'GetEnumerator' // foreach(var item in lazyNonsense) {} Diagnostic(ErrorCode.ERR_ForEachMissingMember, "lazyNonsense").WithArguments("System.Lazy<Nonsense>", "GetEnumerator").WithLocation(19, 29), // (21,37): error CS0246: The type or namespace name 'Nonsense' could not be found (are you missing a using directive or an assembly reference?) // var listNonsense = new List<Nonsense>(); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Nonsense").WithArguments("Nonsense").WithLocation(21, 37), // (25,33): error CS0246: The type or namespace name 'Nonsense' could not be found (are you missing a using directive or an assembly reference?) // var nonsenseArray = new Nonsense[0]; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Nonsense").WithArguments("Nonsense").WithLocation(25, 33), // (29,41): error CS0426: The type name 'Nonsense' does not exist in the type 'string' // var stringNonsense = new String.Nonsense(); Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, "Nonsense").WithArguments("Nonsense", "string").WithLocation(29, 41), // (33,34): error CS0246: The type or namespace name 'Nonsense' could not be found (are you missing a using directive or an assembly reference?) // var nonsenseString = new Nonsense.String(); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Nonsense").WithArguments("Nonsense").WithLocation(33, 34), // (37,9): error CS0246: The type or namespace name 'Nonsense' could not be found (are you missing a using directive or an assembly reference?) // Nonsense? nullableNonsense = default; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Nonsense").WithArguments("Nonsense").WithLocation(37, 9), // (39,29): error CS1579: foreach statement cannot operate on variables of type 'Nonsense?' because 'Nonsense?' does not contain a public instance or extension definition for 'GetEnumerator' // foreach(var item in nullableNonsense) {} Diagnostic(ErrorCode.ERR_ForEachMissingMember, "nullableNonsense").WithArguments("Nonsense?", "GetEnumerator").WithLocation(39, 29), // (41,34): error CS0246: The type or namespace name 'Nonsense' could not be found (are you missing a using directive or an assembly reference?) // var nonsenseTuple = (new Nonsense(), 42); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Nonsense").WithArguments("Nonsense").WithLocation(41, 34), // (43,29): error CS1579: foreach statement cannot operate on variables of type '(Nonsense, int)' because '(Nonsense, int)' does not contain a public instance or extension definition for 'GetEnumerator' // foreach(var item in nonsenseTuple) {} Diagnostic(ErrorCode.ERR_ForEachMissingMember, "nonsenseTuple").WithArguments("(Nonsense, int)", "GetEnumerator").WithLocation(43, 29)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { /// <summary> /// Tests related to binding (but not lowering) foreach loops. /// </summary> public class ForEachTests : CompilingTestBase { [Fact] public void TestErrorBadElementType() { // See bug 7419. var text = @" class C { static void Main() { System.Collections.IEnumerable sequence = null; foreach (MissingType x in sequence) { bool b = !x.Equals(null); } } }"; CreateCompilation(text).VerifyDiagnostics( // (7,18): error CS0246: The type or namespace name 'MissingType' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "MissingType").WithArguments("MissingType")); } [Fact] public void TestErrorNullLiteralCollection() { var text = @" class C { static void Main() { foreach (int x in null) { } } }"; CreateCompilation(text).VerifyDiagnostics( // (6,27): error CS0186: Use of null is not valid in this context Diagnostic(ErrorCode.ERR_NullNotValid, "null")); } [Fact] public void TestErrorNullConstantCollection() { var text = @" class C { static void Main() { const object NULL = null; foreach (int x in NULL) { } } }"; CreateCompilation(text).VerifyDiagnostics( // (7,27): error CS1579: foreach statement cannot operate on variables of type 'object' because 'object' does not contain a public instance or extension definition for 'GetEnumerator' // foreach (int x in NULL) Diagnostic(ErrorCode.ERR_ForEachMissingMember, "NULL").WithArguments("object", "GetEnumerator").WithLocation(7, 27) ); } [WorkItem(540957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540957")] [Fact] public void TestErrorDefaultOfArrayType() { var text = @" class C { static void Main() { foreach (int x in default(int[])) { } } }"; CreateCompilation(text).VerifyDiagnostics( // (7,27): error CS0186: Use of null is not valid in this context Diagnostic(ErrorCode.ERR_NullNotValid, "default(int[])")); } [Fact] public void TestErrorLambdaCollection() { var text = @" class C { static void Main() { foreach (int x in (() => {})) { } } }"; CreateCompilation(text).VerifyDiagnostics( // (6,27): error CS0446: Foreach cannot operate on a 'lambda expression'. Did you intend to invoke the 'lambda expression'? Diagnostic(ErrorCode.ERR_AnonMethGrpInForEach, "(() => {})").WithArguments("lambda expression")); } [Fact] public void TestErrorMethodGroupCollection() { var text = @" class C { static void Main() { foreach (int x in Main) { } } }"; CreateCompilation(text).VerifyDiagnostics( // (6,27): error CS0446: Foreach cannot operate on a 'method group'. Did you intend to invoke the 'method group'? Diagnostic(ErrorCode.ERR_AnonMethGrpInForEach, "Main").WithArguments("method group")); } [Fact] public void TestErrorNoElementConversion() { var text = @" class C { static void Main(string[] args) { foreach (int x in args) { } } }"; CreateCompilation(text).VerifyDiagnostics( // (6,9): error CS0030: Cannot convert type 'string' to 'int' Diagnostic(ErrorCode.ERR_NoExplicitConv, "foreach").WithArguments("string", "int")); } [Fact] public void TestErrorPatternNoGetEnumerator() { var text = @" class C { static void Main(string[] args) { foreach (int x in new Enumerable()) { } } } class Enumerable { //public Enumerator GetEnumerator() { return new Enumerator(); } } class Enumerator { public int Current { get { return 1; } } public bool MoveNext() { return false; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,27): error CS1579: foreach statement cannot operate on variables of type 'Enumerable' because 'Enumerable' does not contain a public definition for 'GetEnumerator' Diagnostic(ErrorCode.ERR_ForEachMissingMember, "new Enumerable()").WithArguments("Enumerable", "GetEnumerator")); } [Fact] public void TestErrorPatternInaccessibleGetEnumerator() { var text = @" class C { static void Main(string[] args) { foreach (int x in new Enumerable()) { } } } class Enumerable { private Enumerator GetEnumerator() { return new Enumerator(); } } class Enumerator { public int Current { get { return 1; } } public bool MoveNext() { return false; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,27): error CS1579: foreach statement cannot operate on variables of type 'Enumerable' because 'Enumerable' does not contain a public definition for 'GetEnumerator' Diagnostic(ErrorCode.ERR_ForEachMissingMember, "new Enumerable()").WithArguments("Enumerable", "GetEnumerator")); } [Fact] public void TestErrorPatternNonPublicGetEnumerator() { var text = @" class C { static void Main(string[] args) { foreach (int x in new Enumerable()) { } } } class Enumerable { internal Enumerator GetEnumerator() { return new Enumerator(); } } class Enumerator { public int Current { get { return 1; } } public bool MoveNext() { return false; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,27): warning CS0279: 'Enumerable' does not implement the 'collection' pattern. 'Enumerable.GetEnumerator()' is not a public instance or extension method. Diagnostic(ErrorCode.WRN_PatternNotPublicOrNotInstance, "new Enumerable()").WithArguments("Enumerable", "collection", "Enumerable.GetEnumerator()"), // (6,27): error CS1579: foreach statement cannot operate on variables of type 'Enumerable' because 'Enumerable' does not contain a public definition for 'GetEnumerator' Diagnostic(ErrorCode.ERR_ForEachMissingMember, "new Enumerable()").WithArguments("Enumerable", "GetEnumerator")); } [Fact] public void TestErrorPatternStaticGetEnumerator() { var text = @" class C { static void Main(string[] args) { foreach (int x in new Enumerable()) { } } } class Enumerable { public static Enumerator GetEnumerator() { return new Enumerator(); } } class Enumerator { public int Current { get { return 1; } } public bool MoveNext() { return false; } } "; CreateCompilation(text, parseOptions: TestOptions.Regular7).VerifyDiagnostics( // (6,27): warning CS0279: 'Enumerable' does not implement the 'collection' pattern. 'Enumerable.GetEnumerator()' is not a public instance or extension method. Diagnostic(ErrorCode.WRN_PatternNotPublicOrNotInstance, "new Enumerable()").WithArguments("Enumerable", "collection", "Enumerable.GetEnumerator()"), // (6,27): error CS1579: foreach statement cannot operate on variables of type 'Enumerable' because 'Enumerable' does not contain a public definition for 'GetEnumerator' Diagnostic(ErrorCode.ERR_ForEachMissingMember, "new Enumerable()").WithArguments("Enumerable", "GetEnumerator")); CreateCompilation(text).VerifyDiagnostics( // (6,27): error CS1579: foreach statement cannot operate on variables of type 'Enumerable' because 'Enumerable' does not contain a public instance or extension definition for 'GetEnumerator' Diagnostic(ErrorCode.ERR_ForEachMissingMember, "new Enumerable()").WithArguments("Enumerable", "GetEnumerator")); } [Fact] public void TestErrorPatternNullableGetEnumerator() { var text = @" struct C { static void Goo(Enumerable? e) { foreach (long x in e) { } } static void Main() { Goo(new Enumerable()); } } struct Enumerable { public Enumerator? GetEnumerator() { return new Enumerator(); } } struct Enumerator { public int Current { get { return 1; } } public bool MoveNext() { return false; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,28): error CS0117: 'Enumerator?' does not contain a definition for 'Current' Diagnostic(ErrorCode.ERR_NoSuchMember, "e").WithArguments("Enumerator?", "Current"), // (6,28): error CS0202: foreach requires that the return type 'Enumerator?' of 'Enumerable.GetEnumerator()' must have a suitable public MoveNext method and public Current property Diagnostic(ErrorCode.ERR_BadGetEnumerator, "e").WithArguments("Enumerator?", "Enumerable.GetEnumerator()")); } [Fact] public void TestErrorPatternNoCurrent() { var text = @" class C { static void Main(string[] args) { foreach (int x in new Enumerable()) { } } } class Enumerable { public Enumerator GetEnumerator() { return new Enumerator(); } } class Enumerator { //public int Current { get { return 1; } } public bool MoveNext() { return false; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,27): error CS0117: 'Enumerator' does not contain a definition for 'Current' Diagnostic(ErrorCode.ERR_NoSuchMember, "new Enumerable()").WithArguments("Enumerator", "Current"), // (6,27): error CS0202: foreach requires that the return type 'Enumerator' of 'Enumerable.GetEnumerator()' must have a suitable public MoveNext method and public Current property Diagnostic(ErrorCode.ERR_BadGetEnumerator, "new Enumerable()").WithArguments("Enumerator", "Enumerable.GetEnumerator()")); } [Fact] public void TestErrorPatternInaccessibleCurrent() { var text = @" class C { static void Main(string[] args) { foreach (int x in new Enumerable()) { } } } class Enumerable { public Enumerator GetEnumerator() { return new Enumerator(); } } class Enumerator { private int Current { get { return 1; } } public bool MoveNext() { return false; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,27): error CS0122: 'Enumerator.Current' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "new Enumerable()").WithArguments("Enumerator.Current"), // (6,27): error CS0202: foreach requires that the return type 'Enumerator' of 'Enumerable.GetEnumerator()' must have a suitable public MoveNext method and public Current property Diagnostic(ErrorCode.ERR_BadGetEnumerator, "new Enumerable()").WithArguments("Enumerator", "Enumerable.GetEnumerator()")); } [Fact] public void TestErrorPatternNonPublicCurrent() { var text = @" class C { static void Main(string[] args) { foreach (int x in new Enumerable()) { } } } class Enumerable { public Enumerator GetEnumerator() { return new Enumerator(); } } class Enumerator { internal int Current { get { return 1; } } public bool MoveNext() { return false; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,27): error CS0202: foreach requires that the return type 'Enumerator' of 'Enumerable.GetEnumerator()' must have a suitable public MoveNext method and public Current property Diagnostic(ErrorCode.ERR_BadGetEnumerator, "new Enumerable()").WithArguments("Enumerator", "Enumerable.GetEnumerator()")); } [Fact] public void TestErrorPatternStaticCurrent() { var text = @" class C { static void Main(string[] args) { foreach (int x in new Enumerable()) { } } } class Enumerable { public Enumerator GetEnumerator() { return new Enumerator(); } } class Enumerator { public static int Current { get { return 1; } } public bool MoveNext() { return false; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,27): error CS0202: foreach requires that the return type 'Enumerator' of 'Enumerable.GetEnumerator()' must have a suitable public MoveNext method and public Current property Diagnostic(ErrorCode.ERR_BadGetEnumerator, "new Enumerable()").WithArguments("Enumerator", "Enumerable.GetEnumerator()")); } [Fact] public void TestErrorPatternNonPropertyCurrent() { var text = @" class C { static void Main(string[] args) { foreach (int x in new Enumerable()) { } } } class Enumerable { public Enumerator GetEnumerator() { return new Enumerator(); } } class Enumerator { public int Current; public bool MoveNext() { return false; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,27): error CS0202: foreach requires that the return type 'Enumerator' of 'Enumerable.GetEnumerator()' must have a suitable public MoveNext method and public Current property // foreach (int x in new Enumerable()) Diagnostic(ErrorCode.ERR_BadGetEnumerator, "new Enumerable()").WithArguments("Enumerator", "Enumerable.GetEnumerator()"), // (19,16): warning CS0649: Field 'Enumerator.Current' is never assigned to, and will always have its default value 0 // public int Current; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Current").WithArguments("Enumerator.Current", "0") ); } [Fact] public void TestErrorPatternNoMoveNext() { var text = @" class C { static void Main(string[] args) { foreach (int x in new Enumerable()) { } } } class Enumerable { public Enumerator GetEnumerator() { return new Enumerator(); } } class Enumerator { public int Current { get { return 1; } } //public bool MoveNext() { return false; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,27): error CS0117: 'Enumerator' does not contain a definition for 'MoveNext' Diagnostic(ErrorCode.ERR_NoSuchMember, "new Enumerable()").WithArguments("Enumerator", "MoveNext"), // (6,27): error CS0202: foreach requires that the return type 'Enumerator' of 'Enumerable.GetEnumerator()' must have a suitable public MoveNext method and public Current property Diagnostic(ErrorCode.ERR_BadGetEnumerator, "new Enumerable()").WithArguments("Enumerator", "Enumerable.GetEnumerator()")); } [Fact] public void TestErrorPatternInaccessibleMoveNext() { var text = @" class C { static void Main(string[] args) { foreach (int x in new Enumerable()) { } } } class Enumerable { public Enumerator GetEnumerator() { return new Enumerator(); } } class Enumerator { public int Current { get { return 1; } } private bool MoveNext() { return false; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,27): error CS0122: 'Enumerator.MoveNext()' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "new Enumerable()").WithArguments("Enumerator.MoveNext()"), // (6,27): error CS0202: foreach requires that the return type 'Enumerator' of 'Enumerable.GetEnumerator()' must have a suitable public MoveNext method and public Current property Diagnostic(ErrorCode.ERR_BadGetEnumerator, "new Enumerable()").WithArguments("Enumerator", "Enumerable.GetEnumerator()")); } [Fact] public void TestErrorPatternNonPublicMoveNext() { var text = @" class C { static void Main(string[] args) { foreach (int x in new Enumerable()) { } } } class Enumerable { public Enumerator GetEnumerator() { return new Enumerator(); } } class Enumerator { public int Current { get { return 1; } } internal bool MoveNext() { return false; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,27): error CS0202: foreach requires that the return type 'Enumerator' of 'Enumerable.GetEnumerator()' must have a suitable public 'MoveNext' method and public 'Current' property // foreach (int x in new Enumerable()) Diagnostic(ErrorCode.ERR_BadGetEnumerator, "new Enumerable()").WithArguments("Enumerator", "Enumerable.GetEnumerator()").WithLocation(6, 27) ); } [Fact] public void TestErrorPatternStaticMoveNext() { var text = @" class C { static void Main(string[] args) { foreach (int x in new Enumerable()) { } } } class Enumerable { public Enumerator GetEnumerator() { return new Enumerator(); } } class Enumerator { public int Current { get { return 1; } } public static bool MoveNext() { return false; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,27): error CS0202: foreach requires that the return type 'Enumerator' of 'Enumerable.GetEnumerator()' must have a suitable public MoveNext method and public Current property Diagnostic(ErrorCode.ERR_BadGetEnumerator, "new Enumerable()").WithArguments("Enumerator", "Enumerable.GetEnumerator()")); } [Fact] public void TestErrorPatternNonMethodMoveNext() { var text = @" class C { static void Main(string[] args) { foreach (int x in new Enumerable()) { } } } class Enumerable { public Enumerator GetEnumerator() { return new Enumerator(); } } class Enumerator { public int Current { get { return 1; } } public bool MoveNext; } "; CreateCompilation(text).VerifyDiagnostics( // (6,27): error CS0202: foreach requires that the return type 'Enumerator' of 'Enumerable.GetEnumerator()' must have a suitable public MoveNext method and public Current property // foreach (int x in new Enumerable()) Diagnostic(ErrorCode.ERR_BadGetEnumerator, "new Enumerable()").WithArguments("Enumerator", "Enumerable.GetEnumerator()"), // (20,17): warning CS0649: Field 'Enumerator.MoveNext' is never assigned to, and will always have its default value false // public bool MoveNext; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "MoveNext").WithArguments("Enumerator.MoveNext", "false") ); } [Fact] public void TestErrorPatternNonBoolMoveNext() { var text = @" class C { static void Main(string[] args) { foreach (int x in new Enumerable()) { } } } class Enumerable { public Enumerator GetEnumerator() { return new Enumerator(); } } class Enumerator { public int Current { get { return 1; } } public int MoveNext() { return 1; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,27): error CS0202: foreach requires that the return type 'Enumerator' of 'Enumerable.GetEnumerator()' must have a suitable public MoveNext method and public Current property Diagnostic(ErrorCode.ERR_BadGetEnumerator, "new Enumerable()").WithArguments("Enumerator", "Enumerable.GetEnumerator()")); } [Fact] public void TestErrorPatternNullableBoolMoveNext() { var text = @" class C { static void Main(string[] args) { foreach (int x in new Enumerable()) { } } } class Enumerable { public Enumerator GetEnumerator() { return new Enumerator(); } } class Enumerator { public int Current { get { return 1; } } public bool? MoveNext() { return true; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,27): error CS0202: foreach requires that the return type 'Enumerator' of 'Enumerable.GetEnumerator()' must have a suitable public MoveNext method and public Current property Diagnostic(ErrorCode.ERR_BadGetEnumerator, "new Enumerable()").WithArguments("Enumerator", "Enumerable.GetEnumerator()")); } [Fact] public void TestErrorPatternNoMoveNextOrCurrent() { var text = @" class C { static void Main(string[] args) { foreach (int x in new Enumerable()) { } } } class Enumerable { public Enumerator GetEnumerator() { return new Enumerator(); } } class Enumerator { //public int Current { get { return 1; } } //public bool MoveNext() { return false; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,27): error CS0117: 'Enumerator' does not contain a definition for 'Current' Diagnostic(ErrorCode.ERR_NoSuchMember, "new Enumerable()").WithArguments("Enumerator", "Current"), // (6,27): error CS0202: foreach requires that the return type 'Enumerator' of 'Enumerable.GetEnumerator()' must have a suitable public MoveNext method and public Current property Diagnostic(ErrorCode.ERR_BadGetEnumerator, "new Enumerable()").WithArguments("Enumerator", "Enumerable.GetEnumerator()")); } [Fact] public void TestErrorMultipleIEnumerableT() { var text = @" using System.Collections; using System.Collections.Generic; class C { void Goo(Enumerable e) { foreach (int x in e) { } } } class Enumerable : IEnumerable<int>, IEnumerable<float> { IEnumerator<float> IEnumerable<float>.GetEnumerator() { throw null; } IEnumerator<int> IEnumerable<int>.GetEnumerator() { throw null; } IEnumerator IEnumerable.GetEnumerator() { throw null; } } "; CreateCompilation(text).VerifyDiagnostics( // (9,27): error CS1640: foreach statement cannot operate on variables of type 'Enumerable' because it implements multiple instantiations of 'System.Collections.Generic.IEnumerable<T>'; try casting to a specific interface instantiation Diagnostic(ErrorCode.ERR_MultipleIEnumOfT, "e").WithArguments("Enumerable", "System.Collections.Generic.IEnumerable<T>")); } [Fact] public void TestErrorMultipleIEnumerableT2() { var text = @" using System.Collections; using System.Collections.Generic; class C { void Goo(Enumerable e) { foreach (int x in e) { } } } class Enumerable : IEnumerable<int>, I { IEnumerator<float> IEnumerable<float>.GetEnumerator() { throw null; } IEnumerator<int> IEnumerable<int>.GetEnumerator() { throw null; } IEnumerator IEnumerable.GetEnumerator() { throw null; } } interface I : IEnumerable<float> { } "; CreateCompilation(text).VerifyDiagnostics( // (9,27): error CS1640: foreach statement cannot operate on variables of type 'Enumerable' because it implements multiple instantiations of 'System.Collections.Generic.IEnumerable<T>'; try casting to a specific interface instantiation Diagnostic(ErrorCode.ERR_MultipleIEnumOfT, "e").WithArguments("Enumerable", "System.Collections.Generic.IEnumerable<T>")); } /// <summary> /// Type parameter with constraints containing /// IEnumerable&lt;T&gt; with explicit implementations. /// </summary> [Fact] public void TestErrorExplicitIEnumerableTOnTypeParameter() { var text = @"using System.Collections; using System.Collections.Generic; struct S { } interface I : IEnumerable<S> { } class A : IEnumerable<int> { IEnumerator<int> IEnumerable<int>.GetEnumerator() { return null; } IEnumerator IEnumerable.GetEnumerator() { return null; } } class B : A, I { IEnumerator<S> IEnumerable<S>.GetEnumerator() { return null; } IEnumerator IEnumerable.GetEnumerator() { return null; } } class C { static void M<T1, T2, T3, T4, T5, T6>(A a, B b, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6) where T1 : A where T2 : B where T3 : I where T4 : T1, I where T5 : A, I where T6 : A, IEnumerable<string> { foreach (int o in a) { } foreach (var o in b) { } foreach (int o in t1) { } foreach (var o in t2) { } foreach (S o in t3) { } foreach (S o in t4) { } foreach (S o in t5) { } foreach (string o in t6) { } } }"; CreateCompilation(text).VerifyDiagnostics( // (26,27): error CS1640: foreach statement cannot operate on variables of type 'B' because it implements multiple instantiations of 'System.Collections.Generic.IEnumerable<T>'; try casting to a specific interface instantiation Diagnostic(ErrorCode.ERR_MultipleIEnumOfT, "b").WithArguments("B", "System.Collections.Generic.IEnumerable<T>").WithLocation(26, 27), // (28,27): error CS1640: foreach statement cannot operate on variables of type 'T2' because it implements multiple instantiations of 'System.Collections.Generic.IEnumerable<T>'; try casting to a specific interface instantiation Diagnostic(ErrorCode.ERR_MultipleIEnumOfT, "t2").WithArguments("T2", "System.Collections.Generic.IEnumerable<T>").WithLocation(28, 27)); } /// <summary> /// Type parameter with constraints containing /// IEnumerable&lt;T&gt; with implicit implementations. /// </summary> [Fact] public void TestErrorImplicitIEnumerableTOnTypeParameter() { var text = @"using System.Collections; using System.Collections.Generic; struct S { } interface I : IEnumerable<S> { } class A : IEnumerable<int> { public IEnumerator<int> GetEnumerator() { return null; } IEnumerator IEnumerable.GetEnumerator() { return null; } } class B : A, I { public new IEnumerator<S> GetEnumerator() { return null; } IEnumerator IEnumerable.GetEnumerator() { return null; } } class C { static void M<T1, T2, T3, T4, T5, T6>(A a, B b, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6) where T1 : A where T2 : B where T3 : I where T4 : T1, I where T5 : A, I where T6 : A, IEnumerable<string> { foreach (int o in a) { } foreach (var o in b) { } foreach (int o in t1) { } foreach (var o in t2) { } foreach (S o in t3) { } foreach (int o in t4) { } foreach (S o in t5) { } foreach (string o in t6) { } } }"; CreateCompilation(text).VerifyDiagnostics( // (31,9): error CS0030: Cannot convert type 'int' to 'S' Diagnostic(ErrorCode.ERR_NoExplicitConv, "foreach").WithArguments("int", "S").WithLocation(31, 9), // (32,9): error CS0030: Cannot convert type 'int' to 'string' Diagnostic(ErrorCode.ERR_NoExplicitConv, "foreach").WithArguments("int", "string").WithLocation(32, 9)); } /// <summary> /// Type parameter with constraints /// using enumerable pattern. /// </summary> [Fact] public void TestErrorEnumerablePatternOnTypeParameter() { var text = @"using System.Collections.Generic; interface I { IEnumerator<object> GetEnumerator(); } class E : I { IEnumerator<object> I.GetEnumerator() { return null; } } class C { static void M<T, U, V>(T t, U u, V v) where T : E where U : E, I where V : T, I { foreach (var o in t) { } foreach (var o in u) { } foreach (var o in v) { } } }"; CreateCompilation(text).VerifyDiagnostics( // (17,27): error CS1579: foreach statement cannot operate on variables of type 'T' because 'T' does not contain a public definition for 'GetEnumerator' Diagnostic(ErrorCode.ERR_ForEachMissingMember, "t").WithArguments("T", "GetEnumerator").WithLocation(17, 27)); } [Fact] public void TestErrorNonEnumerable() { var text = @" class C { void Goo(int i) { foreach (int x in i) { } } } "; CreateCompilation(text).VerifyDiagnostics( // (6,27): error CS1579: foreach statement cannot operate on variables of type 'int' because 'int' does not contain a public definition for 'GetEnumerator' Diagnostic(ErrorCode.ERR_ForEachMissingMember, "i").WithArguments("int", "GetEnumerator")); } [Fact] public void TestErrorModifyIterationVariable() { var text = @" class C { void Goo(int[] a) { foreach (int x in a) { x++; } } } "; CreateCompilation(text).VerifyDiagnostics( // (6,32): error CS1656: Cannot assign to 'x' because it is a 'foreach iteration variable' Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "x").WithArguments("x", "foreach iteration variable")); } [Fact] public void TestErrorImplicitlyTypedCycle() { var text = @" class C { System.Collections.IEnumerable Goo(object y) { foreach (var x in Goo(x)) { } return null; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,31): error CS0103: The name 'x' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x")); } [Fact] public void TestErrorDynamicEnumerator() { var text = @" class C { void Goo(DynamicEnumerable e) { foreach (int x in e) { } } } public class DynamicEnumerable { public dynamic GetEnumerator() { return null; } } "; // It's not entirely clear why this doesn't work, but it doesn't work in Dev10 either. CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (6,27): error CS0117: 'dynamic' does not contain a definition for 'Current' Diagnostic(ErrorCode.ERR_NoSuchMember, "e").WithArguments("dynamic", "Current"), // (6,27): error CS0202: foreach requires that the return type 'dynamic' of 'DynamicEnumerable.GetEnumerator()' must have a suitable public MoveNext method and public Current property Diagnostic(ErrorCode.ERR_BadGetEnumerator, "e").WithArguments("dynamic", "DynamicEnumerable.GetEnumerator()")); } [Fact] public void TestErrorTypeEnumerable() { var text = @" class C { static void Main() { foreach (var x in System.Collections.IEnumerable) { } } } "; // It's not entirely clear why this doesn't work, but it doesn't work in Dev10 either. CreateCompilation(text).VerifyDiagnostics( // (6,27): error CS0119: 'System.Collections.IEnumerable' is a 'type', which is not valid in the given context // foreach (var x in System.Collections.IEnumerable) { } Diagnostic(ErrorCode.ERR_BadSKunknown, "System.Collections.IEnumerable").WithArguments("System.Collections.IEnumerable", "type")); } [Fact] public void TestErrorTypeNonEnumerable() { var text = @" class C { void Goo() { foreach (int x in System.Console) { } } } "; // It's not entirely clear why this doesn't work, but it doesn't work in Dev10 either. CreateCompilation(text).VerifyDiagnostics( // (6,27): error CS0119: 'System.Console' is a 'type', which is not valid in the given context // foreach (int x in System.Console) { } Diagnostic(ErrorCode.ERR_BadSKunknown, "System.Console").WithArguments("System.Console", "type")); } [WorkItem(545123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545123")] [Fact] public void TestErrorForEachLoopWithSyntaxErrors() { string source = @" public static partial class Extensions { public static ((System.Linq.Expressions.Expression<System.Func<int>>)(() => int )).Compile()()Fib(this int i) { } } public class ExtensionMethodTest { public static void Run() { int i = 0; var Fib = new[] { i++.Fib() }; foreach (var j in Fib) { } } }"; Assert.NotEmpty(CreateCompilation(source).GetDiagnostics()); } [WorkItem(545123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545123")] [Fact] public void TestErrorForEachOverVoidArray1() { string source = @" class C { static void Main() { var array = new[] { Main() }; foreach (var element in array) { } } } "; CreateCompilation(source).VerifyDiagnostics( // (6,21): error CS0826: No best type found for implicitly-typed array // var array = new[] { Main() }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { Main() }")); } [WorkItem(545123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545123")] [Fact] public void TestErrorForEachOverVoidArray2() { string source = @" class C { static void Main() { var array = new[] { Main() }; foreach (int element in array) { } } } "; CreateCompilation(source).VerifyDiagnostics( // (6,21): error CS0826: No best type found for implicitly-typed array // var array = new[] { Main() }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { Main() }"), // CONSIDER: Could eliminate this cascading diagnostic. // (7,9): error CS0030: Cannot convert type '?' to 'int' // foreach (int element in array) Diagnostic(ErrorCode.ERR_NoExplicitConv, "foreach").WithArguments("?", "int")); } [WorkItem(545123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545123")] [Fact] public void TestErrorForEachWithVoidIterationVariable() { string source = @" class C { static void Main() { foreach (void element in new int[1]) { } } } "; CreateCompilation(source).VerifyDiagnostics( // (6,18): error CS1547: Keyword 'void' cannot be used in this context // foreach (void element in new int[1]) Diagnostic(ErrorCode.ERR_NoVoidHere, "void").WithLocation(6, 18), // (6,9): error CS0030: Cannot convert type 'int' to 'void' // foreach (void element in new int[1]) Diagnostic(ErrorCode.ERR_NoExplicitConv, "foreach").WithArguments("int", "void").WithLocation(6, 9) ); } [WorkItem(545123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545123")] [Fact] public void TestErrorForEachOverErrorTypeArray() { string source = @" class C { static void Main() { foreach (var element in new Unknown[1]) { } } } "; CreateCompilation(source).VerifyDiagnostics( // (6,37): error CS0246: The type or namespace name 'Unknown' could not be found (are you missing a using directive or an assembly reference?) // foreach (var element in new Unknown[1]) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Unknown").WithArguments("Unknown")); } [Fact] public void TestSuccessArray() { var text = @" class C { void Goo(int[] a) { foreach (int x in a) { } } } "; var boundNode = GetBoundForEachStatement(text); ForEachEnumeratorInfo info = boundNode.EnumeratorInfoOpt; Assert.NotNull(info); Assert.Equal("System.Collections.IEnumerable", info.CollectionType.ToTestDisplayString()); //NB: differs from expression type Assert.Equal(SpecialType.System_Int32, info.ElementTypeWithAnnotations.SpecialType); Assert.Equal("System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()", info.GetEnumeratorInfo.Method.ToTestDisplayString()); Assert.Empty(info.GetEnumeratorInfo.Arguments); Assert.Equal("System.Object System.Collections.IEnumerator.Current.get", info.CurrentPropertyGetter.ToTestDisplayString()); Assert.Equal("System.Boolean System.Collections.IEnumerator.MoveNext()", info.MoveNextInfo.Method.ToTestDisplayString()); Assert.Empty(info.MoveNextInfo.Arguments); Assert.True(info.NeedsDisposal); Assert.Equal(ConversionKind.ImplicitReference, info.CollectionConversion.Kind); Assert.Equal(ConversionKind.Unboxing, info.CurrentConversion.Kind); Assert.Equal(ConversionKind.ImplicitReference, info.EnumeratorConversion.Kind); Assert.Equal(ConversionKind.Identity, boundNode.ElementConversion.Kind); Assert.Equal("System.Int32 x", boundNode.IterationVariables.Single().ToTestDisplayString()); Assert.Equal(SpecialType.System_Collections_IEnumerable, boundNode.Expression.Type.SpecialType); Assert.Equal(SymbolKind.ArrayType, ((BoundConversion)boundNode.Expression).Operand.Type.Kind); } [Fact] public void TestSuccessString() { var text = @" class C { void Goo(string s) { foreach (char c in s) { } } } "; var boundNode = GetBoundForEachStatement(text); ForEachEnumeratorInfo info = boundNode.EnumeratorInfoOpt; Assert.NotNull(info); Assert.Equal(SpecialType.System_String, info.CollectionType.SpecialType); Assert.Equal(SpecialType.System_Char, info.ElementTypeWithAnnotations.SpecialType); Assert.Equal("System.CharEnumerator System.String.GetEnumerator()", info.GetEnumeratorInfo.Method.ToTestDisplayString()); Assert.Empty(info.GetEnumeratorInfo.Arguments); Assert.Equal("System.Char System.CharEnumerator.Current.get", info.CurrentPropertyGetter.ToTestDisplayString()); Assert.Equal("System.Boolean System.CharEnumerator.MoveNext()", info.MoveNextInfo.Method.ToTestDisplayString()); Assert.Empty(info.MoveNextInfo.Arguments); Assert.True(info.NeedsDisposal); Assert.Equal(ConversionKind.Identity, info.CollectionConversion.Kind); Assert.Equal(ConversionKind.Identity, info.CurrentConversion.Kind); Assert.Equal(ConversionKind.ImplicitReference, info.EnumeratorConversion.Kind); Assert.Equal(ConversionKind.Identity, boundNode.ElementConversion.Kind); Assert.Equal("System.Char c", boundNode.IterationVariables.Single().ToTestDisplayString()); Assert.Equal(SpecialType.System_String, boundNode.Expression.Type.SpecialType); Assert.Equal(SpecialType.System_String, ((BoundConversion)boundNode.Expression).Operand.Type.SpecialType); } [Fact] public void TestSuccessPattern() { var text = @" class C { void Goo(Enumerable e) { foreach (long x in e) { } } } class Enumerable { public Enumerator GetEnumerator() { return new Enumerator(); } } class Enumerator { public int Current { get { return 1; } } public bool MoveNext() { return false; } } "; var boundNode = GetBoundForEachStatement(text); ForEachEnumeratorInfo info = boundNode.EnumeratorInfoOpt; Assert.NotNull(info); Assert.Equal("Enumerable", info.CollectionType.ToTestDisplayString()); Assert.Equal(SpecialType.System_Int32, info.ElementTypeWithAnnotations.SpecialType); Assert.Equal("Enumerator Enumerable.GetEnumerator()", info.GetEnumeratorInfo.Method.ToTestDisplayString()); Assert.Empty(info.GetEnumeratorInfo.Arguments); Assert.Equal("System.Int32 Enumerator.Current.get", info.CurrentPropertyGetter.ToTestDisplayString()); Assert.Equal("System.Boolean Enumerator.MoveNext()", info.MoveNextInfo.Method.ToTestDisplayString()); Assert.Empty(info.MoveNextInfo.Arguments); Assert.True(info.NeedsDisposal); Assert.Equal(ConversionKind.Identity, info.CollectionConversion.Kind); Assert.Equal(ConversionKind.Identity, info.CurrentConversion.Kind); Assert.Equal(ConversionKind.ImplicitReference, info.EnumeratorConversion.Kind); Assert.Equal(ConversionKind.ImplicitNumeric, boundNode.ElementConversion.Kind); Assert.Equal("System.Int64 x", boundNode.IterationVariables.Single().ToTestDisplayString()); Assert.Equal("Enumerable", boundNode.Expression.Type.ToTestDisplayString()); Assert.Equal("Enumerable", ((BoundConversion)boundNode.Expression).Operand.Type.ToTestDisplayString()); } [Fact] public void TestSuccessPatternStruct() { var text = @" struct C { void Goo(Enumerable e) { foreach (long x in e) { } } } struct Enumerable { public Enumerator GetEnumerator() { return new Enumerator(); } } struct Enumerator { public int Current { get { return 1; } } public bool MoveNext() { return false; } } "; var boundNode = GetBoundForEachStatement(text); ForEachEnumeratorInfo info = boundNode.EnumeratorInfoOpt; Assert.NotNull(info); Assert.Equal("Enumerable", info.CollectionType.ToTestDisplayString()); Assert.Equal(SpecialType.System_Int32, info.ElementTypeWithAnnotations.SpecialType); Assert.Equal("Enumerator Enumerable.GetEnumerator()", info.GetEnumeratorInfo.Method.ToTestDisplayString()); Assert.Empty(info.GetEnumeratorInfo.Arguments); Assert.Equal("System.Int32 Enumerator.Current.get", info.CurrentPropertyGetter.ToTestDisplayString()); Assert.Equal("System.Boolean Enumerator.MoveNext()", info.MoveNextInfo.Method.ToTestDisplayString()); Assert.Empty(info.MoveNextInfo.Arguments); Assert.False(info.NeedsDisposal); // Definitely not disposable Assert.Equal(ConversionKind.Identity, info.CollectionConversion.Kind); Assert.Equal(ConversionKind.Identity, info.CurrentConversion.Kind); Assert.Equal(ConversionKind.Identity, info.EnumeratorConversion.Kind); Assert.Equal(ConversionKind.ImplicitNumeric, boundNode.ElementConversion.Kind); Assert.Equal("System.Int64 x", boundNode.IterationVariables.Single().ToTestDisplayString()); Assert.Equal("Enumerable", boundNode.Expression.Type.ToTestDisplayString()); Assert.Equal("Enumerable", ((BoundConversion)boundNode.Expression).Operand.Type.ToTestDisplayString()); } [Fact] public void TestSuccessInterfacePattern() { var text = @" class C { void Goo(System.Collections.IEnumerable e) { foreach (long x in e) { } } } "; var boundNode = GetBoundForEachStatement(text); ForEachEnumeratorInfo info = boundNode.EnumeratorInfoOpt; Assert.NotNull(info); Assert.Equal("System.Collections.IEnumerable", info.CollectionType.ToTestDisplayString()); Assert.Equal(SpecialType.System_Object, info.ElementTypeWithAnnotations.SpecialType); Assert.Equal("System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()", info.GetEnumeratorInfo.Method.ToTestDisplayString()); Assert.Empty(info.GetEnumeratorInfo.Arguments); Assert.Equal("System.Object System.Collections.IEnumerator.Current.get", info.CurrentPropertyGetter.ToTestDisplayString()); Assert.Equal("System.Boolean System.Collections.IEnumerator.MoveNext()", info.MoveNextInfo.Method.ToTestDisplayString()); Assert.Empty(info.MoveNextInfo.Arguments); Assert.True(info.NeedsDisposal); Assert.Equal(ConversionKind.Identity, info.CollectionConversion.Kind); Assert.Equal(ConversionKind.Identity, info.CurrentConversion.Kind); Assert.Equal(ConversionKind.ImplicitReference, info.EnumeratorConversion.Kind); Assert.Equal(ConversionKind.Unboxing, boundNode.ElementConversion.Kind); Assert.Equal("System.Int64 x", boundNode.IterationVariables.Single().ToTestDisplayString()); Assert.Equal("System.Collections.IEnumerable", boundNode.Expression.Type.ToTestDisplayString()); Assert.Equal("System.Collections.IEnumerable", ((BoundConversion)boundNode.Expression).Operand.Type.ToTestDisplayString()); } [Fact] public void TestSuccessInterfaceNonPatternGeneric() { var text = @" class C { void Goo(Enumerable e) { foreach (long x in e) { } } } class Enumerable : System.Collections.Generic.IEnumerable<int> { // Explicit implementations won't match pattern. System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return null; } System.Collections.Generic.IEnumerator<int> System.Collections.Generic.IEnumerable<int>.GetEnumerator() { return null; } } "; var boundNode = GetBoundForEachStatement(text); ForEachEnumeratorInfo info = boundNode.EnumeratorInfoOpt; Assert.NotNull(info); Assert.Equal("System.Collections.Generic.IEnumerable<System.Int32>", info.CollectionType.ToTestDisplayString()); //NB: differs from expression type Assert.Equal(SpecialType.System_Int32, info.ElementTypeWithAnnotations.SpecialType); Assert.Equal("System.Collections.Generic.IEnumerator<System.Int32> System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator()", info.GetEnumeratorInfo.Method.ToTestDisplayString()); Assert.Empty(info.GetEnumeratorInfo.Arguments); Assert.Equal("System.Int32 System.Collections.Generic.IEnumerator<System.Int32>.Current.get", info.CurrentPropertyGetter.ToTestDisplayString()); Assert.Equal("System.Boolean System.Collections.IEnumerator.MoveNext()", info.MoveNextInfo.Method.ToTestDisplayString()); //NB: not on generic interface Assert.Empty(info.MoveNextInfo.Arguments); Assert.True(info.NeedsDisposal); Assert.Equal(ConversionKind.ImplicitReference, info.CollectionConversion.Kind); Assert.Equal(ConversionKind.Identity, info.CurrentConversion.Kind); Assert.Equal(ConversionKind.ImplicitReference, info.EnumeratorConversion.Kind); Assert.Equal(ConversionKind.ImplicitNumeric, boundNode.ElementConversion.Kind); Assert.Equal("System.Int64 x", boundNode.IterationVariables.Single().ToTestDisplayString()); Assert.Equal("System.Collections.Generic.IEnumerable<System.Int32>", boundNode.Expression.Type.ToTestDisplayString()); Assert.Equal("Enumerable", ((BoundConversion)boundNode.Expression).Operand.Type.ToTestDisplayString()); } [Fact] public void TestSuccessInterfaceNonPatternInaccessibleGeneric() { var text = @" class C { void Goo(Enumerable e) { foreach (object x in e) { } } } class Enumerable : System.Collections.Generic.IEnumerable<Enumerable.Hidden> { // Explicit implementations won't match pattern. System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return null; } System.Collections.Generic.IEnumerator<Hidden> System.Collections.Generic.IEnumerable<Hidden>.GetEnumerator() { return null; } private class Hidden { } } "; var boundNode = GetBoundForEachStatement(text); ForEachEnumeratorInfo info = boundNode.EnumeratorInfoOpt; Assert.NotNull(info); Assert.Equal("System.Collections.IEnumerable", info.CollectionType.ToTestDisplayString()); //NB: fall back on non-generic, since generic is inaccessible Assert.Equal(SpecialType.System_Object, info.ElementTypeWithAnnotations.SpecialType); Assert.Equal("System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()", info.GetEnumeratorInfo.Method.ToTestDisplayString()); Assert.Empty(info.GetEnumeratorInfo.Arguments); Assert.Equal("System.Object System.Collections.IEnumerator.Current.get", info.CurrentPropertyGetter.ToTestDisplayString()); Assert.Equal("System.Boolean System.Collections.IEnumerator.MoveNext()", info.MoveNextInfo.Method.ToTestDisplayString()); Assert.Empty(info.MoveNextInfo.Arguments); Assert.True(info.NeedsDisposal); Assert.Equal(ConversionKind.ImplicitReference, info.CollectionConversion.Kind); Assert.Equal(ConversionKind.Identity, info.CurrentConversion.Kind); Assert.Equal(ConversionKind.ImplicitReference, info.EnumeratorConversion.Kind); Assert.Equal(ConversionKind.Identity, boundNode.ElementConversion.Kind); Assert.Equal("System.Object x", boundNode.IterationVariables.Single().ToTestDisplayString()); Assert.Equal(SpecialType.System_Collections_IEnumerable, boundNode.Expression.Type.SpecialType); Assert.Equal("Enumerable", ((BoundConversion)boundNode.Expression).Operand.Type.ToTestDisplayString()); } [Fact] public void TestSuccessInterfaceNonPatternNonGeneric() { var text = @" class C { void Goo(Enumerable e) { foreach (long x in e) { } } } class Enumerable : System.Collections.IEnumerable { // Explicit implementation won't match pattern. System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return null; } } "; var boundNode = GetBoundForEachStatement(text); ForEachEnumeratorInfo info = boundNode.EnumeratorInfoOpt; Assert.NotNull(info); Assert.Equal("System.Collections.IEnumerable", info.CollectionType.ToTestDisplayString()); //NB: differs from expression type Assert.Equal(SpecialType.System_Object, info.ElementTypeWithAnnotations.SpecialType); Assert.Equal("System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()", info.GetEnumeratorInfo.Method.ToTestDisplayString()); Assert.Empty(info.GetEnumeratorInfo.Arguments); Assert.Equal("System.Object System.Collections.IEnumerator.Current.get", info.CurrentPropertyGetter.ToTestDisplayString()); Assert.Equal("System.Boolean System.Collections.IEnumerator.MoveNext()", info.MoveNextInfo.Method.ToTestDisplayString()); Assert.Empty(info.MoveNextInfo.Arguments); Assert.True(info.NeedsDisposal); Assert.Equal(ConversionKind.ImplicitReference, info.CollectionConversion.Kind); Assert.Equal(ConversionKind.Identity, info.CurrentConversion.Kind); Assert.Equal(ConversionKind.ImplicitReference, info.EnumeratorConversion.Kind); Assert.Equal(ConversionKind.Unboxing, boundNode.ElementConversion.Kind); Assert.Equal("System.Int64 x", boundNode.IterationVariables.Single().ToTestDisplayString()); Assert.Equal(SpecialType.System_Collections_IEnumerable, boundNode.Expression.Type.SpecialType); Assert.Equal("Enumerable", ((BoundConversion)boundNode.Expression).Operand.Type.ToTestDisplayString()); } [Fact] public void TestSuccessImplicitlyTypedArray() { var text = @" class C { void Goo(int[] a) { foreach (var x in a) { } } } "; var boundNode = GetBoundForEachStatement(text); ForEachEnumeratorInfo info = boundNode.EnumeratorInfoOpt; Assert.NotNull(info); Assert.Equal("System.Collections.IEnumerable", info.CollectionType.ToTestDisplayString()); //NB: differs from expression type Assert.Equal(SpecialType.System_Int32, info.ElementTypeWithAnnotations.SpecialType); Assert.Equal("System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()", info.GetEnumeratorInfo.Method.ToTestDisplayString()); Assert.Empty(info.GetEnumeratorInfo.Arguments); Assert.Equal("System.Object System.Collections.IEnumerator.Current.get", info.CurrentPropertyGetter.ToTestDisplayString()); Assert.Equal("System.Boolean System.Collections.IEnumerator.MoveNext()", info.MoveNextInfo.Method.ToTestDisplayString()); Assert.Empty(info.MoveNextInfo.Arguments); Assert.True(info.NeedsDisposal); Assert.Equal(ConversionKind.ImplicitReference, info.CollectionConversion.Kind); Assert.Equal(ConversionKind.Unboxing, info.CurrentConversion.Kind); Assert.Equal(ConversionKind.ImplicitReference, info.EnumeratorConversion.Kind); Assert.Equal(ConversionKind.Identity, boundNode.ElementConversion.Kind); Assert.Equal(SpecialType.System_Int32, boundNode.IterationVariables.Single().Type.SpecialType); } [Fact] public void TestSuccessImplicitlyTypedString() { var text = @" class C { void Goo(string s) { foreach (var x in s) { } } } "; var boundNode = GetBoundForEachStatement(text); ForEachEnumeratorInfo info = boundNode.EnumeratorInfoOpt; Assert.NotNull(info); Assert.Equal(SpecialType.System_String, info.CollectionType.SpecialType); Assert.Equal(SpecialType.System_Char, info.ElementTypeWithAnnotations.SpecialType); Assert.Equal("System.CharEnumerator System.String.GetEnumerator()", info.GetEnumeratorInfo.Method.ToTestDisplayString()); Assert.Empty(info.GetEnumeratorInfo.Arguments); Assert.Equal("System.Char System.CharEnumerator.Current.get", info.CurrentPropertyGetter.ToTestDisplayString()); Assert.Equal("System.Boolean System.CharEnumerator.MoveNext()", info.MoveNextInfo.Method.ToTestDisplayString()); Assert.Empty(info.MoveNextInfo.Arguments); Assert.True(info.NeedsDisposal); Assert.Equal(ConversionKind.Identity, info.CollectionConversion.Kind); Assert.Equal(ConversionKind.Identity, info.CurrentConversion.Kind); Assert.Equal(ConversionKind.ImplicitReference, info.EnumeratorConversion.Kind); Assert.Equal(ConversionKind.Identity, boundNode.ElementConversion.Kind); Assert.Equal(SpecialType.System_Char, boundNode.IterationVariables.Single().Type.SpecialType); } [Fact] public void TestSuccessImplicitlyTypedPattern() { var text = @" class C { void Goo(Enumerable e) { foreach (var x in e) { } } } class Enumerable { public Enumerator GetEnumerator() { return new Enumerator(); } } class Enumerator { public int Current { get { return 1; } } public bool MoveNext() { return false; } } "; var boundNode = GetBoundForEachStatement(text); Assert.NotNull(boundNode.EnumeratorInfoOpt); Assert.Equal(ConversionKind.Identity, boundNode.ElementConversion.Kind); Assert.Equal(SpecialType.System_Int32, boundNode.IterationVariables.Single().Type.SpecialType); } [Fact] public void TestSuccessImplicitlyTypedInterface() { var text = @" class C { void Goo(Enumerable e) { foreach (var x in e) { } } } class Enumerable : System.Collections.IEnumerable { // Explicit implementation won't match pattern. System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return null; } } "; var boundNode = GetBoundForEachStatement(text); Assert.NotNull(boundNode.EnumeratorInfoOpt); Assert.Equal(ConversionKind.Identity, boundNode.ElementConversion.Kind); Assert.Equal(SpecialType.System_Object, boundNode.IterationVariables.Single().Type.SpecialType); } [Fact] public void TestSuccessExplicitlyTypedVar() { var text = @" class C { void Goo(var[] a) { foreach (var x in a) { } } class var { } } "; var boundNode = GetBoundForEachStatement(text); ForEachEnumeratorInfo info = boundNode.EnumeratorInfoOpt; Assert.NotNull(info); Assert.Equal("System.Collections.IEnumerable", info.CollectionType.ToTestDisplayString()); //NB: differs from expression type Assert.Equal("C.var", info.ElementTypeWithAnnotations.ToTestDisplayString()); Assert.Equal("System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()", info.GetEnumeratorInfo.Method.ToTestDisplayString()); Assert.Empty(info.GetEnumeratorInfo.Arguments); Assert.Equal("System.Object System.Collections.IEnumerator.Current.get", info.CurrentPropertyGetter.ToTestDisplayString()); Assert.Equal("System.Boolean System.Collections.IEnumerator.MoveNext()", info.MoveNextInfo.Method.ToTestDisplayString()); Assert.Empty(info.MoveNextInfo.Arguments); Assert.True(info.NeedsDisposal); Assert.Equal(ConversionKind.ImplicitReference, info.CollectionConversion.Kind); Assert.Equal(ConversionKind.ExplicitReference, info.CurrentConversion.Kind); //object to C.var Assert.Equal(ConversionKind.ImplicitReference, info.EnumeratorConversion.Kind); Assert.Equal(ConversionKind.Identity, boundNode.ElementConversion.Kind); Assert.Equal("C.var", boundNode.IterationVariables.Single().TypeWithAnnotations.ToTestDisplayString()); } [Fact] public void TestSuccessDynamicEnumerable() { var text = @" class C { void Goo(dynamic d) { foreach (int x in d) { } } } "; var boundNode = GetBoundForEachStatement(text); ForEachEnumeratorInfo info = boundNode.EnumeratorInfoOpt; Assert.NotNull(info); Assert.Equal(SpecialType.System_Collections_IEnumerable, info.CollectionType.SpecialType); Assert.Equal(SpecialType.System_Object, info.ElementTypeWithAnnotations.SpecialType); Assert.Equal("System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()", info.GetEnumeratorInfo.Method.ToTestDisplayString()); Assert.Empty(info.GetEnumeratorInfo.Arguments); Assert.Equal("System.Object System.Collections.IEnumerator.Current.get", info.CurrentPropertyGetter.ToTestDisplayString()); Assert.Equal("System.Boolean System.Collections.IEnumerator.MoveNext()", info.MoveNextInfo.Method.ToTestDisplayString()); Assert.Empty(info.MoveNextInfo.Arguments); Assert.True(info.NeedsDisposal); Assert.Equal(ConversionKind.ImplicitDynamic, info.CollectionConversion.Kind); Assert.Equal(ConversionKind.Identity, info.CurrentConversion.Kind); Assert.Equal(ConversionKind.ImplicitReference, info.EnumeratorConversion.Kind); Assert.Equal(ConversionKind.ExplicitDynamic, boundNode.ElementConversion.Kind); Assert.Equal("System.Int32 x", boundNode.IterationVariables.Single().ToTestDisplayString()); Assert.Equal(SpecialType.System_Collections_IEnumerable, boundNode.Expression.Type.SpecialType); Assert.Equal(TypeKind.Dynamic, ((BoundConversion)boundNode.Expression).Operand.Type.TypeKind); } [Fact] public void TestSuccessImplicitlyTypedDynamicEnumerable() { var text = @" class C { void Goo(dynamic d) { foreach (var x in d) { } } } "; var boundNode = GetBoundForEachStatement(text); ForEachEnumeratorInfo info = boundNode.EnumeratorInfoOpt; Assert.NotNull(info); Assert.Equal(SpecialType.System_Collections_IEnumerable, info.CollectionType.SpecialType); Assert.Equal(TypeKind.Dynamic, info.ElementType.TypeKind); //NB: differs from explicit case Assert.Equal("System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()", info.GetEnumeratorInfo.Method.ToTestDisplayString()); Assert.Empty(info.GetEnumeratorInfo.Arguments); Assert.Equal("System.Object System.Collections.IEnumerator.Current.get", info.CurrentPropertyGetter.ToTestDisplayString()); Assert.Equal("System.Boolean System.Collections.IEnumerator.MoveNext()", info.MoveNextInfo.Method.ToTestDisplayString()); Assert.Empty(info.MoveNextInfo.Arguments); Assert.True(info.NeedsDisposal); Assert.Equal(ConversionKind.ImplicitDynamic, info.CollectionConversion.Kind); Assert.Equal(ConversionKind.Identity, info.CurrentConversion.Kind); Assert.Equal(ConversionKind.ImplicitReference, info.EnumeratorConversion.Kind); Assert.Equal(ConversionKind.Identity, boundNode.ElementConversion.Kind); //NB: differs from explicit case Assert.Equal("dynamic x", boundNode.IterationVariables.Single().ToTestDisplayString()); Assert.Equal(SpecialType.System_Collections_IEnumerable, boundNode.Expression.Type.SpecialType); Assert.Equal(SymbolKind.DynamicType, ((BoundConversion)boundNode.Expression).Operand.Type.Kind); } [Fact] public void TestSuccessTypeParameterConstrainedToInterface() { var text = @" class C { static void Test<T>() where T : System.Collections.IEnumerator { foreach (object x in new Enumerable<T>()) { System.Console.WriteLine(x); } } } public class Enumerable<T> { public T GetEnumerator() { return default(T); } } "; var boundNode = GetBoundForEachStatement(text); ForEachEnumeratorInfo info = boundNode.EnumeratorInfoOpt; Assert.NotNull(info); Assert.Equal("Enumerable<T>", info.CollectionType.ToTestDisplayString()); Assert.Equal(SpecialType.System_Object, info.ElementTypeWithAnnotations.SpecialType); Assert.Equal("T Enumerable<T>.GetEnumerator()", info.GetEnumeratorInfo.Method.ToTestDisplayString()); Assert.Empty(info.GetEnumeratorInfo.Arguments); Assert.Equal("System.Object System.Collections.IEnumerator.Current.get", info.CurrentPropertyGetter.ToTestDisplayString()); Assert.Equal("System.Boolean System.Collections.IEnumerator.MoveNext()", info.MoveNextInfo.Method.ToTestDisplayString()); Assert.Empty(info.MoveNextInfo.Arguments); Assert.True(info.NeedsDisposal); Assert.Equal(ConversionKind.Identity, info.CollectionConversion.Kind); Assert.Equal(ConversionKind.Identity, info.CurrentConversion.Kind); Assert.Equal(ConversionKind.Boxing, info.EnumeratorConversion.Kind); Assert.Equal(ConversionKind.Identity, boundNode.ElementConversion.Kind); Assert.Equal("System.Object x", boundNode.IterationVariables.Single().ToTestDisplayString()); Assert.Equal("Enumerable<T>", boundNode.Expression.Type.ToTestDisplayString()); Assert.Equal("Enumerable<T>", ((BoundConversion)boundNode.Expression).Operand.Type.ToTestDisplayString()); } [Fact] public void TestSuccessTypeParameterConstrainedToClass() { var text = @"using System.Collections; using System.Collections.Generic; class A<T> : IEnumerable<T> { IEnumerator<T> IEnumerable<T>.GetEnumerator() { return null; } IEnumerator IEnumerable.GetEnumerator() { return null; } } class A0 : A<string> { } class C<T> { static void M<U, V>(A0 a, U u, V v) where U : A0 where V : A<T> { foreach (var o in a) { M<string>(o); } foreach (var o in u) { M<string>(o); } foreach (var o in v) { M<T>(o); } } static void M<U>(U u) { } }"; var compilation = CreateCompilation(text); compilation.VerifyDiagnostics(); } [Fact] public void TestSuccessTypeParameterConstrainedToPattern() { var text = @" class C { static void Test<T>() where T : MyEnumerator { foreach (object x in new Enumerable<T>()) { System.Console.WriteLine(x); } } } public class Enumerable<T> { public T GetEnumerator() { return default(T); } } interface MyEnumerator { object Current { get; } bool MoveNext(); } "; var boundNode = GetBoundForEachStatement(text); ForEachEnumeratorInfo info = boundNode.EnumeratorInfoOpt; Assert.NotNull(info); Assert.Equal("Enumerable<T>", info.CollectionType.ToTestDisplayString()); Assert.Equal(SpecialType.System_Object, info.ElementTypeWithAnnotations.SpecialType); Assert.Equal("T Enumerable<T>.GetEnumerator()", info.GetEnumeratorInfo.Method.ToTestDisplayString()); Assert.Empty(info.GetEnumeratorInfo.Arguments); Assert.Equal("System.Object MyEnumerator.Current.get", info.CurrentPropertyGetter.ToTestDisplayString()); Assert.Equal("System.Boolean MyEnumerator.MoveNext()", info.MoveNextInfo.Method.ToTestDisplayString()); Assert.Empty(info.MoveNextInfo.Arguments); Assert.True(info.NeedsDisposal); Assert.Equal(ConversionKind.Identity, info.CollectionConversion.Kind); Assert.Equal(ConversionKind.Identity, info.CurrentConversion.Kind); Assert.Equal(ConversionKind.Boxing, info.EnumeratorConversion.Kind); Assert.Equal(ConversionKind.Identity, boundNode.ElementConversion.Kind); Assert.Equal("System.Object x", boundNode.IterationVariables.Single().ToTestDisplayString()); Assert.Equal("Enumerable<T>", boundNode.Expression.Type.ToTestDisplayString()); Assert.Equal("Enumerable<T>", ((BoundConversion)boundNode.Expression).Operand.Type.ToTestDisplayString()); } // Copied from TestSuccessPatternStruct - only change is that Goo parameter is now nullable. [WorkItem(544908, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544908")] [Fact] public void TestSuccessNullableCollection() { var text = @" struct C { void Goo(Enumerable? e) { foreach (long x in e) { } } } struct Enumerable { public Enumerator GetEnumerator() { return new Enumerator(); } } struct Enumerator { public int Current { get { return 1; } } public bool MoveNext() { return false; } } "; var boundNode = GetBoundForEachStatement(text); // NOTE: info is exactly as if the collection was not nullable. ForEachEnumeratorInfo info = boundNode.EnumeratorInfoOpt; Assert.NotNull(info); Assert.Equal("Enumerable", info.CollectionType.ToTestDisplayString()); Assert.Equal(SpecialType.System_Int32, info.ElementTypeWithAnnotations.SpecialType); Assert.Equal("Enumerator Enumerable.GetEnumerator()", info.GetEnumeratorInfo.Method.ToTestDisplayString()); Assert.Empty(info.GetEnumeratorInfo.Arguments); Assert.Equal("System.Int32 Enumerator.Current.get", info.CurrentPropertyGetter.ToTestDisplayString()); Assert.Equal("System.Boolean Enumerator.MoveNext()", info.MoveNextInfo.Method.ToTestDisplayString()); Assert.Empty(info.MoveNextInfo.Arguments); Assert.False(info.NeedsDisposal); // Definitely not disposable Assert.Equal(ConversionKind.Identity, info.CollectionConversion.Kind); Assert.Equal(ConversionKind.Identity, info.CurrentConversion.Kind); Assert.Equal(ConversionKind.Identity, info.EnumeratorConversion.Kind); Assert.Equal(ConversionKind.ImplicitNumeric, boundNode.ElementConversion.Kind); Assert.Equal("System.Int64 x", boundNode.IterationVariables.Single().ToTestDisplayString()); Assert.Equal("Enumerable", boundNode.Expression.Type.ToTestDisplayString()); Assert.Equal("Enumerable", ((BoundConversion)boundNode.Expression).Operand.Type.ToTestDisplayString()); } [WorkItem(542193, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542193")] [Fact] public void ForEachStmtWithSyntaxError1() { var text = @" public class Test { public static void Main(string [] args) { foreach(int; i < 5; i++) { } } } "; var boundNode = GetBoundForEachStatement(text, TestOptions.Regular, // (6,13): error CS1525: Invalid expression term 'int' // foreach(int; i < 5; i++) Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(6, 13), // (6,16): error CS1515: 'in' expected // foreach(int; i < 5; i++) Diagnostic(ErrorCode.ERR_InExpected, ";").WithLocation(6, 16), // (6,16): error CS0230: Type and identifier are both required in a foreach statement // foreach(int; i < 5; i++) Diagnostic(ErrorCode.ERR_BadForeachDecl, ";").WithLocation(6, 16), // (6,16): error CS1525: Invalid expression term ';' // foreach(int; i < 5; i++) Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(6, 16), // (6,16): error CS1026: ) expected // foreach(int; i < 5; i++) Diagnostic(ErrorCode.ERR_CloseParenExpected, ";").WithLocation(6, 16), // (6,28): error CS1002: ; expected // foreach(int; i < 5; i++) Diagnostic(ErrorCode.ERR_SemicolonExpected, ")").WithLocation(6, 28), // (6,28): error CS1513: } expected // foreach(int; i < 5; i++) Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(6, 28), // (6,18): error CS0103: The name 'i' does not exist in the current context // foreach(int; i < 5; i++) Diagnostic(ErrorCode.ERR_NameNotInContext, "i").WithArguments("i").WithLocation(6, 18), // (6,18): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // foreach(int; i < 5; i++) Diagnostic(ErrorCode.ERR_IllegalStatement, "i < 5").WithLocation(6, 18), // (6,25): error CS0103: The name 'i' does not exist in the current context // foreach(int; i < 5; i++) Diagnostic(ErrorCode.ERR_NameNotInContext, "i").WithArguments("i").WithLocation(6, 25)); Assert.Null(boundNode.EnumeratorInfoOpt); } [WorkItem(545489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545489")] [Fact] public void ForEachOnErrorTypesWithoutReferences() { var text = @" public class condGenClass<T> { } public class Test { static void Main() { Type[] types = {typeof(condGenClass<int>)}; foreach (Type t in types) { } } } "; var compilation = CreateEmptyCompilation(text); Assert.NotEmpty(compilation.GetDiagnostics()); } [WorkItem(545489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545489")] [Fact] public void ForEachWithoutCorlib_Array() { var text = @" public class Test { static void Main() { Test[] array = new Test[] { new Test() }; foreach (Test t in array) { } } } "; var compilation = CreateEmptyCompilation(text); Assert.NotEmpty(compilation.GetDiagnostics()); } [WorkItem(545489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545489")] [Fact] public void ForEachWithoutCorlib_String() { var text = @" public class Test { static void Main() { foreach (char ch in ""hello"") { } } } "; var compilation = CreateEmptyCompilation(text); Assert.NotEmpty(compilation.GetDiagnostics()); } [WorkItem(545186, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545186")] [Fact] public void TestForEachWithConditionalMethod() { string source = @" using System; using System.Collections; namespace ForEachTest { public class BaseEnumerator { public bool MoveNext() { Console.WriteLine(""BaseEnumerator::MoveNext()""); return false; } public int Current { get { Console.WriteLine(""BaseEnumerator::Current""); return 1; } } } public class BaseEnumeratorImpl : IEnumerator { public bool MoveNext() { Console.WriteLine(""BaseEnumeratorImpl::MoveNext()""); return false; } public Object Current { get { Console.WriteLine(""BaseEnumeratorImpl::Current""); return 1; } } public void Reset() { Console.WriteLine(""BaseEnumeratorImpl::Reset""); } } public class BasePattern { public BaseEnumerator GetEnumerator() { Console.WriteLine(""BasePattern::GetEnumerator()""); return new BaseEnumerator(); } } namespace ValidBaseTest { public class Derived5 : BasePattern, IEnumerable { IEnumerator IEnumerable.GetEnumerator() { Console.WriteLine(""<Interface> Derived5.GetEnumerator()""); return new BaseEnumeratorImpl(); } [System.Diagnostics.Conditional(""CONDITIONAL"")] new public void GetEnumerator() { Console.WriteLine(""ERROR: <Conditional Method not in scope> Derived5.GetEnumerator()""); } } } public class Logger { public static void Main() { foreach (int i in new ValidBaseTest.Derived5()) { } } } } "; // Without "CONDITIONAL" defined: Succeed string expectedOutput = @"<Interface> Derived5.GetEnumerator() BaseEnumeratorImpl::MoveNext()"; CompileAndVerify(source, expectedOutput: expectedOutput); // With "CONDITIONAL" defined: Fail // (a) Preprocessor symbol defined through command line parse options var options = new CSharpParseOptions(preprocessorSymbols: ImmutableArray.Create("CONDITIONAL"), documentationMode: DocumentationMode.None); CreateCompilation(source, parseOptions: options).VerifyDiagnostics( // (35,31): error CS0117: 'void' does not contain a definition for 'Current' // foreach (int i in new ValidBaseTest.Derived5()) { } Diagnostic(ErrorCode.ERR_NoSuchMember, "new ValidBaseTest.Derived5()").WithArguments("void", "Current").WithLocation(35, 31), // (35,31): error CS0202: foreach requires that the return type 'void' of 'ForEachTest.ValidBaseTest.Derived5.GetEnumerator()' must have a suitable public MoveNext method and public Current property // foreach (int i in new ValidBaseTest.Derived5()) { } Diagnostic(ErrorCode.ERR_BadGetEnumerator, "new ValidBaseTest.Derived5()").WithArguments("void", "ForEachTest.ValidBaseTest.Derived5.GetEnumerator()").WithLocation(35, 31)); // (b) Preprocessor symbol defined in source string condDefSource = "#define CONDITIONAL" + source; CreateCompilation(condDefSource).VerifyDiagnostics( // (35,31): error CS0117: 'void' does not contain a definition for 'Current' // foreach (int i in new ValidBaseTest.Derived5()) { } Diagnostic(ErrorCode.ERR_NoSuchMember, "new ValidBaseTest.Derived5()").WithArguments("void", "Current").WithLocation(35, 31), // (35,31): error CS0202: foreach requires that the return type 'void' of 'ForEachTest.ValidBaseTest.Derived5.GetEnumerator()' must have a suitable public MoveNext method and public Current property // foreach (int i in new ValidBaseTest.Derived5()) { } Diagnostic(ErrorCode.ERR_BadGetEnumerator, "new ValidBaseTest.Derived5()").WithArguments("void", "ForEachTest.ValidBaseTest.Derived5.GetEnumerator()").WithLocation(35, 31)); } [WorkItem(649809, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/649809")] [Fact] public void ArrayOfNullableOfError() { var source = @" class F { void Test() { E[] a1 = null; E?[] a2 = null; S<E>[] a3 = null; IEnumerable<E> e1 = null; IEnumerable<E?> e2 = null; IEnumerable<S<E>> e3 = null; foreach (E e in a1) { } foreach (E e in a2) { } foreach (E e in a2) { } foreach (E e in e1) { } foreach (E e in e2) { } foreach (E? e in a1) { } foreach (E? e in a2) { } // used to assert foreach (E? e in e1) { } foreach (E? e in e2) { } foreach (S<E> e in a3) { } foreach (S<E> e in e3) { } } } public struct S<T> { } "; Assert.NotEmpty(CreateCompilation(source).GetDiagnostics()); } [WorkItem(667616, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/667616")] [Fact] public void PortableLibraryStringForEach() { var source = @" class C { void Test(string s) { foreach (var c in s) { } } } "; var comp = CreateEmptyCompilation(source, new[] { MscorlibRefPortable }); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var loopSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var loopInfo = model.GetForEachStatementInfo(loopSyntax); Assert.False(loopInfo.IsAsynchronous); Assert.Equal<ISymbol>(comp.GetSpecialTypeMember(SpecialMember.System_Collections_IEnumerable__GetEnumerator).GetPublicSymbol(), loopInfo.GetEnumeratorMethod); Assert.Equal<ISymbol>(comp.GetSpecialTypeMember(SpecialMember.System_Collections_IEnumerator__Current).GetPublicSymbol(), loopInfo.CurrentProperty); Assert.Equal<ISymbol>(comp.GetSpecialTypeMember(SpecialMember.System_Collections_IEnumerator__MoveNext).GetPublicSymbol(), loopInfo.MoveNextMethod); Assert.Equal<ISymbol>(comp.GetSpecialTypeMember(SpecialMember.System_IDisposable__Dispose).GetPublicSymbol(), loopInfo.DisposeMethod); // The spec says that the element type is object. // Therefore, we should infer object for "var". Assert.Equal(SpecialType.System_Object, loopInfo.CurrentProperty.Type.SpecialType); // However, to match dev11, we actually infer "char" for "var". var typeInfo = model.GetTypeInfo(loopSyntax.Type); Assert.Equal(SpecialType.System_Char, typeInfo.Type.SpecialType); Assert.Equal(typeInfo.Type, typeInfo.ConvertedType); var conv = model.GetConversion(loopSyntax.Type); Assert.Equal(ConversionKind.Identity, conv.Kind); } [WorkItem(529956, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529956")] [Fact] public void CastArrayToIEnumerable() { var source = @" using System.Collections; class C { static void Main(string[] args) { foreach (C x in args) { } foreach (C x in (IEnumerable)args) { } } public static implicit operator C(string s) { return new C(); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var udc = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>(WellKnownMemberNames.ImplicitConversionName); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var loopSyntaxes = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().ToArray(); Assert.Equal(2, loopSyntaxes.Length); var loopInfo0 = model.GetForEachStatementInfo(loopSyntaxes[0]); Assert.Equal<ISymbol>(comp.GetSpecialTypeMember(SpecialMember.System_Collections_IEnumerable__GetEnumerator).GetPublicSymbol(), loopInfo0.GetEnumeratorMethod); Assert.Equal<ISymbol>(comp.GetSpecialTypeMember(SpecialMember.System_Collections_IEnumerator__Current).GetPublicSymbol(), loopInfo0.CurrentProperty); Assert.Equal<ISymbol>(comp.GetSpecialTypeMember(SpecialMember.System_Collections_IEnumerator__MoveNext).GetPublicSymbol(), loopInfo0.MoveNextMethod); Assert.Equal<ISymbol>(comp.GetSpecialTypeMember(SpecialMember.System_IDisposable__Dispose).GetPublicSymbol(), loopInfo0.DisposeMethod); Assert.Equal(SpecialType.System_String, loopInfo0.ElementType.SpecialType); Assert.Equal(udc, loopInfo0.ElementConversion.Method); Assert.Equal(ConversionKind.ExplicitReference, loopInfo0.CurrentConversion.Kind); var loopInfo1 = model.GetForEachStatementInfo(loopSyntaxes[1]); Assert.Equal(loopInfo0.GetEnumeratorMethod, loopInfo1.GetEnumeratorMethod); Assert.Equal(loopInfo0.CurrentProperty, loopInfo1.CurrentProperty); Assert.Equal(loopInfo0.MoveNextMethod, loopInfo1.MoveNextMethod); Assert.Equal(loopInfo0.DisposeMethod, loopInfo1.DisposeMethod); Assert.Equal(SpecialType.System_Object, loopInfo1.ElementType.SpecialType); // No longer string. Assert.Null(loopInfo1.ElementConversion.Method); // No longer using UDC. Assert.Equal(ConversionKind.Identity, loopInfo1.CurrentConversion.Kind); // Now identity. } [WorkItem(762179, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/762179")] [Fact] public void MissingObjectType() { var text = @" class C { void Goo(Enumerable e) { foreach (Element x in e) { } } } struct Enumerable { public Enumerator GetEnumerator() { return new Enumerator(); } } struct Enumerator { public Element Current { get { return null; } } public bool MoveNext() { return false; } } class Element { } "; var comp = CreateEmptyCompilation(text); comp.GetDiagnostics(); } [WorkItem(798000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/798000")] [WorkItem(39948, "https://github.com/dotnet/roslyn/issues/39948")] [Fact] public void MissingNullableValue() { var text = @" namespace System { public class Object { } public class ValueType {} public struct Void { } public struct Nullable<T> { } public struct Boolean { } } namespace System.Collections.Generic { public interface IEnumerable<T> { IEnumerator<T> GetEnumerator(); } public interface IEnumerator<T> { T Current { get; } bool MoveNext(); } } class C { void Goo(System.Collections.Generic.IEnumerable<C>? e) { foreach (var c in e) { } } } "; var comp = CreateEmptyCompilation(text); comp.VerifyDiagnostics( // (28,55): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // void Goo(System.Collections.Generic.IEnumerable<C>? e) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(28, 55) ); comp.VerifyEmitDiagnostics( // warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options. Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Byte' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1), // (28,55): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // void Goo(System.Collections.Generic.IEnumerable<C>? e) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(28, 55), // The following error is unexpected - https://github.com/dotnet/roslyn/issues/39948 // (30,9): error CS0656: Missing compiler required member 'System.IDisposable.Dispose' // foreach (var c in e) { } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "foreach (var c in e) { }").WithArguments("System.IDisposable", "Dispose").WithLocation(30, 9) ); } [WorkItem(798000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/798000")] [Fact] public void MissingNullableValue_CSharp7() { var text = @" namespace System { public class Object { } public class ValueType {} public struct Void { } public struct Nullable<T> { } public struct Boolean { } } namespace System.Collections.Generic { public interface IEnumerable<T> { IEnumerator<T> GetEnumerator(); } public interface IEnumerator<T> { T Current { get; } bool MoveNext(); } } class C { void Goo(System.Collections.Generic.IEnumerable<C>? e) { foreach (var c in e) { } } } "; var expected = new[] { // (28,55): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater. // void Goo(System.Collections.Generic.IEnumerable<C>? e) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "?").WithArguments("nullable reference types", "8.0").WithLocation(28, 55) }; var comp = CreateEmptyCompilation(text, parseOptions: TestOptions.Regular7_3, skipUsesIsNullable: true); comp.VerifyDiagnostics(expected); comp = CreateEmptyCompilation(text, skipUsesIsNullable: true); comp.VerifyDiagnostics( // (28,55): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // void Goo(System.Collections.Generic.IEnumerable<C>? e) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(28, 55) ); } [WorkItem(798000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/798000")] [Fact] public void MissingIEnumerableTGetEnumerator() { var text = @" namespace System { public class Object { } public class ValueType {} public struct Void { } public struct Boolean { } } namespace System.Collections.Generic { public interface IEnumerable<T> { } } public class Enumerable<T> : System.Collections.Generic.IEnumerable<T> { } class C { void Goo(System.Collections.Generic.IEnumerable<C> e1, Enumerable<C> e2) { foreach (var c in e1) { } // Pattern foreach (var c in e2) { } // Interface } } "; var comp = CreateEmptyCompilation(text); comp.VerifyDiagnostics( // For pattern: // (22,27): error CS1579: foreach statement cannot operate on variables of type 'System.Collections.Generic.IEnumerable<C>' because 'System.Collections.Generic.IEnumerable<C>' does not contain a public definition for 'GetEnumerator' // foreach (var c in e1) { } Diagnostic(ErrorCode.ERR_ForEachMissingMember, "e1").WithArguments("System.Collections.Generic.IEnumerable<C>", "GetEnumerator"), // For interface: // (23,27): error CS0656: Missing compiler required member 'System.Collections.Generic.IEnumerable`1.GetEnumerator' // foreach (var c in e2) { } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "e2").WithArguments("System.Collections.Generic.IEnumerable`1", "GetEnumerator"), // (23,27): error CS0656: Missing compiler required member 'System.Collections.IEnumerator.MoveNext' // foreach (var c in e2) { } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "e2").WithArguments("System.Collections.IEnumerator", "MoveNext")); } [WorkItem(798000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/798000")] [Fact] public void MissingIEnumeratorTMoveNext() { var text = @" namespace System { public class Object { } public class ValueType {} public struct Void { } public struct Boolean { } } namespace System.Collections.Generic { public interface IEnumerable<T> { IEnumerator<T> GetEnumerator(); } public interface IEnumerator<T> { T Current { get; } } } public class Enumerable<T> : System.Collections.Generic.IEnumerable<T> { System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator() { return null; } } class C { void Goo(System.Collections.Generic.IEnumerable<C> e1, Enumerable<C> e2) { foreach (var c in e1) { } // Pattern foreach (var c in e2) { } // Interface } } "; var comp = CreateEmptyCompilation(text); comp.VerifyDiagnostics( // For pattern: // (37,27): error CS0117: 'System.Collections.Generic.IEnumerator<C>' does not contain a definition for 'MoveNext' // foreach (var c in e1) { } // Pattern Diagnostic(ErrorCode.ERR_NoSuchMember, "e1").WithArguments("System.Collections.Generic.IEnumerator<C>", "MoveNext"), // For interface: // (37,27): error CS0202: foreach requires that the return type 'System.Collections.Generic.IEnumerator<C>' of 'System.Collections.Generic.IEnumerable<C>.GetEnumerator()' must have a suitable public MoveNext method and public Current property // foreach (var c in e1) { } // Pattern Diagnostic(ErrorCode.ERR_BadGetEnumerator, "e1").WithArguments("System.Collections.Generic.IEnumerator<C>", "System.Collections.Generic.IEnumerable<C>.GetEnumerator()"), // (38,27): error CS0656: Missing compiler required member 'System.Collections.IEnumerator.MoveNext' // foreach (var c in e2) { } // Interface Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "e2").WithArguments("System.Collections.IEnumerator", "MoveNext")); } [WorkItem(798000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/798000")] [Fact] public void MissingIEnumeratorTCurrent() { var text = @" namespace System { public class Object { } public class ValueType {} public struct Void { } public struct Boolean { } } namespace System.Collections { public interface IEnumerator { bool MoveNext(); } } namespace System.Collections.Generic { public interface IEnumerable<T> { IEnumerator<T> GetEnumerator(); } public interface IEnumerator<T> : IEnumerator { //T Current { get; } } } public class Enumerable<T> : System.Collections.Generic.IEnumerable<T> { System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator() { return null; } } class C { void Goo(System.Collections.Generic.IEnumerable<C> e1, Enumerable<C> e2) { foreach (var c in e1) { } // Pattern foreach (var c in e2) { } // Interface } } "; var comp = CreateEmptyCompilation(text); comp.VerifyDiagnostics( // For pattern: // (44,27): error CS0117: 'System.Collections.Generic.IEnumerator<C>' does not contain a definition for 'Current' // foreach (var c in e1) { } // Pattern Diagnostic(ErrorCode.ERR_NoSuchMember, "e1").WithArguments("System.Collections.Generic.IEnumerator<C>", "Current"), // (44,27): error CS0202: foreach requires that the return type 'System.Collections.Generic.IEnumerator<C>' of 'System.Collections.Generic.IEnumerable<C>.GetEnumerator()' must have a suitable public MoveNext method and public Current property // foreach (var c in e1) { } // Pattern Diagnostic(ErrorCode.ERR_BadGetEnumerator, "e1").WithArguments("System.Collections.Generic.IEnumerator<C>", "System.Collections.Generic.IEnumerable<C>.GetEnumerator()"), // For interface: // (45,27): error CS0656: Missing compiler required member 'System.Collections.Generic.IEnumerator`1.get_Current' // foreach (var c in e2) { } // Interface Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "e2").WithArguments("System.Collections.Generic.IEnumerator`1", "get_Current")); } [WorkItem(798000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/798000")] [Fact] public void MissingIEnumeratorTCurrentGetter() { var text = @" namespace System { public class Object { } public class ValueType {} public struct Void { } public struct Boolean { } } namespace System.Collections { public interface IEnumerator { bool MoveNext(); } } namespace System.Collections.Generic { public interface IEnumerable<T> { IEnumerator<T> GetEnumerator(); } public interface IEnumerator<T> : IEnumerator { T Current { /* get; */ set; } } } public class Enumerable<T> : System.Collections.Generic.IEnumerable<T> { System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator() { return null; } } class C { void Goo(System.Collections.Generic.IEnumerable<C> e1, Enumerable<C> e2) { foreach (var c in e1) { } // Pattern foreach (var c in e2) { } // Interface } } "; var comp = CreateEmptyCompilation(text); comp.VerifyDiagnostics( // For pattern: // (44,27): error CS0202: foreach requires that the return type 'System.Collections.Generic.IEnumerator<C>' of 'System.Collections.Generic.IEnumerable<C>.GetEnumerator()' must have a suitable public MoveNext method and public Current property // foreach (var c in e1) { } // Pattern Diagnostic(ErrorCode.ERR_BadGetEnumerator, "e1").WithArguments("System.Collections.Generic.IEnumerator<C>", "System.Collections.Generic.IEnumerable<C>.GetEnumerator()"), // For interface: // (45,27): error CS0656: Missing compiler required member 'System.Collections.Generic.IEnumerator`1.get_Current' // foreach (var c in e2) { } // Interface Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "e2").WithArguments("System.Collections.Generic.IEnumerator`1", "get_Current")); } [WorkItem(798000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/798000")] [Fact] public void MissingIEnumerableGetEnumerator() { var text = @" namespace System { public class Object { } public class ValueType {} public struct Void { } public struct Boolean { } } namespace System.Collections { public interface IEnumerable { } } public class Enumerable : System.Collections.IEnumerable { } class C { void Goo(System.Collections.IEnumerable e1, Enumerable e2) { foreach (var c in e1) { } // Pattern foreach (var c in e2) { } // Interface } } "; var comp = CreateEmptyCompilation(text); comp.VerifyDiagnostics( // For pattern: // (22,27): error CS1579: foreach statement cannot operate on variables of type 'System.Collections.IEnumerable' because 'System.Collections.IEnumerable' does not contain a public definition for 'GetEnumerator' // foreach (var c in e1) { } Diagnostic(ErrorCode.ERR_ForEachMissingMember, "e1").WithArguments("System.Collections.IEnumerable", "GetEnumerator"), // For interface: // (23,27): error CS0656: Missing compiler required member 'System.Collections.IEnumerable.GetEnumerator' // foreach (var c in e2) { } // Interface Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "e2").WithArguments("System.Collections.IEnumerable", "GetEnumerator"), // (23,27): error CS0656: Missing compiler required member 'System.Collections.IEnumerator.get_Current' // foreach (var c in e2) { } // Interface Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "e2").WithArguments("System.Collections.IEnumerator", "get_Current"), // (23,27): error CS0656: Missing compiler required member 'System.Collections.IEnumerator.MoveNext' // foreach (var c in e2) { } // Interface Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "e2").WithArguments("System.Collections.IEnumerator", "MoveNext")); } [WorkItem(798000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/798000")] [Fact] public void MissingIEnumeratorMoveNext() { var text = @" namespace System { public class Object { } public class ValueType {} public struct Void { } public struct Boolean { } } namespace System.Collections { public interface IEnumerable { IEnumerator GetEnumerator(); } public interface IEnumerator { object Current { get; } } } public class Enumerable : System.Collections.IEnumerable { System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return null; } } class C { void Goo(System.Collections.IEnumerable e1, Enumerable e2) { foreach (var c in e1) { } // Pattern foreach (var c in e2) { } // Interface } } "; var comp = CreateEmptyCompilation(text); comp.VerifyDiagnostics( // For pattern: // (37,27): error CS0117: 'System.Collections.IEnumerator' does not contain a definition for 'MoveNext' // foreach (var c in e1) { } // Pattern Diagnostic(ErrorCode.ERR_NoSuchMember, "e1").WithArguments("System.Collections.IEnumerator", "MoveNext"), // For interface: // (37,27): error CS0202: foreach requires that the return type 'System.Collections.IEnumerator' of 'System.Collections.IEnumerable.GetEnumerator()' must have a suitable public MoveNext method and public Current property // foreach (var c in e1) { } // Pattern Diagnostic(ErrorCode.ERR_BadGetEnumerator, "e1").WithArguments("System.Collections.IEnumerator", "System.Collections.IEnumerable.GetEnumerator()"), // (38,27): error CS0656: Missing compiler required member 'System.Collections.IEnumerator.MoveNext' // foreach (var c in e2) { } // Interface Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "e2").WithArguments("System.Collections.IEnumerator", "MoveNext")); } [WorkItem(798000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/798000")] [Fact] public void MissingIEnumeratorCurrent() { var text = @" namespace System { public class Object { } public class ValueType {} public struct Void { } public struct Boolean { } } namespace System.Collections { public interface IEnumerable { IEnumerator GetEnumerator(); } public interface IEnumerator { bool MoveNext(); //object Current { get; } } } public class Enumerable : System.Collections.IEnumerable { System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return null; } } class C { void Goo(System.Collections.IEnumerable e1, Enumerable e2) { foreach (var c in e1) { } // Pattern foreach (var c in e2) { } // Interface } } "; var comp = CreateEmptyCompilation(text); comp.VerifyDiagnostics( // For pattern: // (44,27): error CS0117: 'System.Collections.IEnumerator' does not contain a definition for 'Current' // foreach (var c in e1) { } // Pattern Diagnostic(ErrorCode.ERR_NoSuchMember, "e1").WithArguments("System.Collections.IEnumerator", "Current"), // (44,27): error CS0202: foreach requires that the return type 'System.Collections.IEnumerator' of 'System.Collections.IEnumerable.GetEnumerator()' must have a suitable public MoveNext method and public Current property // foreach (var c in e1) { } // Pattern Diagnostic(ErrorCode.ERR_BadGetEnumerator, "e1").WithArguments("System.Collections.IEnumerator", "System.Collections.IEnumerable.GetEnumerator()"), // For interface: // (45,27): error CS0656: Missing compiler required member 'System.Collections.IEnumerator.get_Current' // foreach (var c in e2) { } // Interface Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "e2").WithArguments("System.Collections.IEnumerator", "get_Current")); } [WorkItem(798000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/798000")] [Fact] public void MissingIEnumeratorCurrentGetter() { var text = @" namespace System { public class Object { } public class ValueType {} public struct Void { } public struct Boolean { } } namespace System.Collections { public interface IEnumerable { IEnumerator GetEnumerator(); } public interface IEnumerator { bool MoveNext(); object Current { /* get; */ set; } } } public class Enumerable : System.Collections.IEnumerable { System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return null; } } class C { void Goo(System.Collections.IEnumerable e1, Enumerable e2) { foreach (var c in e1) { } // Pattern foreach (var c in e2) { } // Interface } } "; var comp = CreateEmptyCompilation(text); comp.VerifyDiagnostics( // For pattern: // (44,27): error CS0202: foreach requires that the return type 'System.Collections.IEnumerator' of 'System.Collections.IEnumerable.GetEnumerator()' must have a suitable public MoveNext method and public Current property // foreach (var c in e1) { } // Pattern Diagnostic(ErrorCode.ERR_BadGetEnumerator, "e1").WithArguments("System.Collections.IEnumerator", "System.Collections.IEnumerable.GetEnumerator()"), // For interface: // (45,27): error CS0656: Missing compiler required member 'System.Collections.IEnumerator.get_Current' // foreach (var c in e2) { } // Interface Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "e2").WithArguments("System.Collections.IEnumerator", "get_Current")); } [WorkItem(530381, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530381")] [Fact] public void BadCollectionCascadingErrors() { var source = @" class Program { static void Main() { foreach(var x in Goo) { } } } "; CreateCompilation(source).VerifyDiagnostics( // (6,26): error CS0103: The name 'Goo' does not exist in the current context // foreach(var x in Goo) { } Diagnostic(ErrorCode.ERR_NameNotInContext, "Goo").WithArguments("Goo").WithLocation(6, 26)); } [WorkItem(847507, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/847507")] [Fact] public void InferIterationVariableTypeWithErrors() { var source = @" class Program { static void Main() { foreach(var x in new string[1]) { } } } namespace System { public class Object { } public class String : Object { } } "; var comp = CreateEmptyCompilation(source); // Lots of errors, since corlib is missing. var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var foreachSyntax = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var localSymbol = model.GetDeclaredSymbol(foreachSyntax); // Code Path 1: SourceLocalSymbol.Type. var localSymbolType = localSymbol.Type; Assert.Equal(SpecialType.System_String, localSymbolType.SpecialType); Assert.NotEqual(TypeKind.Error, localSymbolType.TypeKind); // Code Path 2: SemanticModel. var varSyntax = foreachSyntax.Type; var info = model.GetSymbolInfo(varSyntax); // Used to assert. Assert.Equal(localSymbolType, info.Symbol); } [WorkItem(667275, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/667275")] [Fact] public void Repro667275() { // This is not the simplest repro, but it is the one from the bug. var source = @" using System.Collections.Generic; class myClass<T> { public static implicit operator T(myClass<T> m) { return default(T); } } class Test { static void Main() { var myObj = new myClass<List<string>>(); foreach (var x in myObj) { } } } "; CreateCompilation(source).VerifyDiagnostics( // (14,27): error CS1579: foreach statement cannot operate on variables of type 'myClass<System.Collections.Generic.List<string>>' because 'myClass<System.Collections.Generic.List<string>>' does not contain a public definition for 'GetEnumerator' // foreach (var x in myObj) { } Diagnostic(ErrorCode.ERR_ForEachMissingMember, "myObj").WithArguments("myClass<System.Collections.Generic.List<string>>", "GetEnumerator").WithLocation(14, 27)); } [WorkItem(667275, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/667275")] [Fact] public void Repro667275_Simplified() { // No generics, no foreach. var source = @" using System.Collections; class Dummy { public static implicit operator MyEnumerable(Dummy d) { return null; } } public class MyEnumerable : IEnumerable { IEnumerator IEnumerable.GetEnumerator() { throw new System.NotImplementedException(); } } class Test { static void Main() { Dummy d = new Dummy(); MyEnumerable m = d; // succeeds IEnumerable i = d; // fails } } "; CreateCompilation(source).VerifyDiagnostics( // (27,25): error CS0266: Cannot implicitly convert type 'Dummy' to 'System.Collections.IEnumerable'. An explicit conversion exists (are you missing a cast?) // IEnumerable i = d; // fails Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "d").WithArguments("Dummy", "System.Collections.IEnumerable").WithLocation(27, 25)); } [WorkItem(963197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/963197")] [Fact] public void Repro963197() { var source = @"using System; class Program { public static string B = ""B""; public static string C = ""C""; static void Main(string[] args) { foreach (var a in new { B, C }) { Console.WriteLine(a); } } }"; CreateCompilation(source).VerifyDiagnostics( // (9,27): error CS1579: foreach statement cannot operate on variables of type '<anonymous type: string B, string C>' because '<anonymous type: string B, string C>' does not contain a public definition for 'GetEnumerator' // foreach (var a in new { B, C }) Diagnostic(ErrorCode.ERR_ForEachMissingMember, "new { B, C }").WithArguments("<anonymous type: string B, string C>", "GetEnumerator").WithLocation(9, 27) ); } [WorkItem(11387, "https://github.com/dotnet/roslyn/issues/11387")] [Fact] public void StringNotIEnumerable() { var source1 = @"namespace System { public class Object { } public struct Void { } public class ValueType { } public struct Boolean { } public struct Int32 { } public struct Char { } public class String { public int Length => 2; [System.Runtime.CompilerServices.IndexerName(""Chars"")] public char this[int i] => 'a'; } public interface IDisposable { void Dispose(); } public abstract class Attribute { protected Attribute() { } } } namespace System.Runtime.CompilerServices { using System; public sealed class IndexerNameAttribute: Attribute { public IndexerNameAttribute(String indexerName) {} } } namespace System.Reflection { using System; public sealed class DefaultMemberAttribute : Attribute { public DefaultMemberAttribute(String memberName) {} } } namespace System.Collections { public interface IEnumerable { IEnumerator GetEnumerator(); } public interface IEnumerator { object Current { get; } bool MoveNext(); } }"; var compilation1 = CreateEmptyCompilation(source1, assemblyName: GetUniqueName()); var reference1 = MetadataReference.CreateFromStream(compilation1.EmitToStream()); var text = @"class C { static void M(string s) { foreach (var c in s) { // comment } } }"; var comp = CreateEmptyCompilation(text, new[] { reference1 }); CompileAndVerify(comp, verify: Verification.Fails). VerifyIL("C.M", @" { // Code size 28 (0x1c) .maxstack 2 .locals init (string V_0, int V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldc.i4.0 IL_0003: stloc.1 IL_0004: br.s IL_0012 IL_0006: ldloc.0 IL_0007: ldloc.1 IL_0008: callvirt ""char string.this[int].get"" IL_000d: pop IL_000e: ldloc.1 IL_000f: ldc.i4.1 IL_0010: add IL_0011: stloc.1 IL_0012: ldloc.1 IL_0013: ldloc.0 IL_0014: callvirt ""int string.Length.get"" IL_0019: blt.s IL_0006 IL_001b: ret } "); var boundNode = GetBoundForEachStatement(text); ForEachEnumeratorInfo info = boundNode.EnumeratorInfoOpt; Assert.NotNull(info); Assert.Equal(SpecialType.System_String, info.CollectionType.SpecialType); Assert.Equal(SpecialType.System_Char, info.ElementTypeWithAnnotations.SpecialType); Assert.Equal("System.CharEnumerator System.String.GetEnumerator()", info.GetEnumeratorInfo.Method.ToTestDisplayString()); Assert.Empty(info.GetEnumeratorInfo.Arguments); Assert.Equal("System.Char System.CharEnumerator.Current.get", info.CurrentPropertyGetter.ToTestDisplayString()); Assert.Equal("System.Boolean System.CharEnumerator.MoveNext()", info.MoveNextInfo.Method.ToTestDisplayString()); Assert.Empty(info.MoveNextInfo.Arguments); Assert.True(info.NeedsDisposal); Assert.Equal(ConversionKind.Identity, info.CollectionConversion.Kind); Assert.Equal(ConversionKind.Identity, info.CurrentConversion.Kind); Assert.Equal(ConversionKind.ImplicitReference, info.EnumeratorConversion.Kind); Assert.Equal(ConversionKind.Identity, boundNode.ElementConversion.Kind); Assert.Equal(SpecialType.System_Char, boundNode.IterationVariables.Single().Type.SpecialType); } [Fact] public void TestPatternDisposeRefStruct() { var text = @" class C { static void Main() { foreach (var x in new Enumerable1()) { System.Console.WriteLine(x); } } } class Enumerable1 { public DisposableEnumerator GetEnumerator() { return new DisposableEnumerator(); } } ref struct DisposableEnumerator { int x; public int Current { get { return x; } } public bool MoveNext() { return ++x < 4; } public void Dispose() { } }"; var boundNode = GetBoundForEachStatement(text); var enumeratorInfo = boundNode.EnumeratorInfoOpt; Assert.Equal("void DisposableEnumerator.Dispose()", enumeratorInfo.PatternDisposeInfo.Method.ToTestDisplayString()); Assert.Empty(enumeratorInfo.PatternDisposeInfo.Arguments); } [Fact] public void TestPatternDisposeRefStruct_7_3() { var text = @" class C { static void Main() { foreach (var x in new Enumerable1()) { System.Console.WriteLine(x); } } } class Enumerable1 { public DisposableEnumerator GetEnumerator() { return new DisposableEnumerator(); } } ref struct DisposableEnumerator { int x; public int Current { get { return x; } } public bool MoveNext() { return ++x < 4; } public void Dispose() { } }"; var boundNode = GetBoundForEachStatement(text, TestOptions.Regular7_3); var enumeratorInfo = boundNode.EnumeratorInfoOpt; Assert.Null(enumeratorInfo.PatternDisposeInfo); } [Fact] public void TestExtensionGetEnumerator() { var text = @" using System; public class C { public static void Main() { foreach (var i in new C()) { Console.Write(i); } } public sealed class Enumerator { public int Current { get; private set; } public bool MoveNext() => Current++ != 3; } } public static class Extensions { public static C.Enumerator GetEnumerator(this C self) => new C.Enumerator(); }"; var boundNode = GetBoundForEachStatement(text, options: TestOptions.Regular9); ForEachEnumeratorInfo info = boundNode.EnumeratorInfoOpt; Assert.NotNull(info); Assert.Equal("C", info.CollectionType.ToTestDisplayString()); Assert.Equal(SpecialType.System_Int32, info.ElementTypeWithAnnotations.SpecialType); Assert.Equal("C.Enumerator Extensions.GetEnumerator(this C self)", info.GetEnumeratorInfo.Method.ToTestDisplayString()); Assert.Equal("C", info.GetEnumeratorInfo.Arguments.Single().Type.ToTestDisplayString()); Assert.Equal("System.Int32 C.Enumerator.Current.get", info.CurrentPropertyGetter.ToTestDisplayString()); Assert.Equal("System.Boolean C.Enumerator.MoveNext()", info.MoveNextInfo.Method.ToTestDisplayString()); Assert.Empty(info.MoveNextInfo.Arguments); Assert.False(info.NeedsDisposal); Assert.Equal(ConversionKind.Identity, info.CollectionConversion.Kind); Assert.Equal(ConversionKind.Identity, info.CurrentConversion.Kind); Assert.Equal(ConversionKind.ImplicitReference, info.EnumeratorConversion.Kind); Assert.Equal(ConversionKind.Identity, boundNode.ElementConversion.Kind); Assert.Equal("System.Int32 i", boundNode.IterationVariables.Single().ToTestDisplayString()); Assert.Equal("C", boundNode.Expression.Type.ToDisplayString()); } private static BoundForEachStatement GetBoundForEachStatement(string text, CSharpParseOptions options = null, params DiagnosticDescription[] diagnostics) { var tree = Parse(text, options: options); var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { tree }); comp.VerifyDiagnostics(diagnostics); var syntaxNode = (CommonForEachStatementSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.ForEachStatement).AsNode() ?? (CommonForEachStatementSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.ForEachVariableStatement).AsNode(); var treeModel = (SyntaxTreeSemanticModel)comp.GetSemanticModel(tree); var memberModel = treeModel.GetMemberModel(syntaxNode); BoundForEachStatement boundNode = (BoundForEachStatement)memberModel.GetUpperBoundNode(syntaxNode); // Make sure that the bound node info is exposed correctly in the API ForEachEnumeratorInfo enumeratorInfo = boundNode.EnumeratorInfoOpt; ForEachStatementInfo statementInfo = treeModel.GetForEachStatementInfo(syntaxNode); if (enumeratorInfo == null) { Assert.Equal(default(ForEachStatementInfo), statementInfo); } else { Assert.Equal(enumeratorInfo.GetEnumeratorInfo.Method.GetPublicSymbol(), statementInfo.GetEnumeratorMethod); Assert.Equal(enumeratorInfo.CurrentPropertyGetter.GetPublicSymbol(), statementInfo.CurrentProperty.GetMethod); Assert.Equal(enumeratorInfo.MoveNextInfo.Method.GetPublicSymbol(), statementInfo.MoveNextMethod); if (enumeratorInfo.NeedsDisposal) { if (enumeratorInfo.PatternDisposeInfo is object) { Assert.Equal(enumeratorInfo.PatternDisposeInfo.Method.GetPublicSymbol(), statementInfo.DisposeMethod); } else if (enumeratorInfo.IsAsync) { Assert.Equal("System.ValueTask System.IAsyncDisposable.DisposeAsync()", statementInfo.DisposeMethod.ToTestDisplayString()); } else { Assert.Equal("void System.IDisposable.Dispose()", statementInfo.DisposeMethod.ToTestDisplayString()); } } else { Assert.Null(statementInfo.DisposeMethod); } Assert.Equal(enumeratorInfo.ElementType.GetPublicSymbol(), statementInfo.ElementType); Assert.Equal(boundNode.ElementConversion, statementInfo.ElementConversion); Assert.Equal(enumeratorInfo.CurrentConversion, statementInfo.CurrentConversion); } return boundNode; } [WorkItem(1100741, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1100741")] [Fact] public void Bug1100741() { var source = @" namespace ImmutableObjectGraph { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using IdentityFieldType = System.UInt32; public static class RecursiveTypeExtensions { /// <summary>Gets the recursive parent of the specified value, or <c>null</c> if none could be found.</summary> internal ParentedRecursiveType<<#= templateType.RecursiveParent.TypeName #>, <#= templateType.RecursiveTypeFromFamily.TypeName #>> GetParentedNode(<#= templateType.RequiredIdentityField.TypeName #> identity) { if (this.Identity == identity) { return new ParentedRecursiveType<<#= templateType.RecursiveParent.TypeName #>, <#= templateType.RecursiveTypeFromFamily.TypeName #>>(this, null); } if (this.LookupTable != null) { System.Collections.Generic.KeyValuePair<<#= templateType.RecursiveType.TypeName #>, <#= templateType.RequiredIdentityField.TypeName #>> lookupValue; if (this.LookupTable.TryGetValue(identity, out lookupValue)) { var parentIdentity = lookupValue.Value; return new ParentedRecursiveType<<#= templateType.RecursiveParent.TypeName #>, <#= templateType.RecursiveTypeFromFamily.TypeName #>>(this.LookupTable[identity].Key, (<#= templateType.RecursiveParent.TypeName #>)this.Find(parentIdentity)); } } else { // No lookup table means we have to aggressively search each child. foreach (var child in this.Children) { if (child.Identity.Equals(identity)) { return new ParentedRecursiveType<<#= templateType.RecursiveParent.TypeName #>, <#= templateType.RecursiveTypeFromFamily.TypeName #>>(child, this); } var recursiveChild = child as <#= templateType.RecursiveParent.TypeName #>; if (recursiveChild != null) { var childResult = recursiveChild.GetParentedNode(identity); if (childResult.Value != null) { return childResult; } } } } return default(ParentedRecursiveType<<#= templateType.RecursiveParent.TypeName #>, <#= templateType.RecursiveTypeFromFamily.TypeName #>>); } } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().Where(n => n.Kind() == SyntaxKind.ForEachStatement).OfType<ForEachStatementSyntax>().Single(); var model = compilation.GetSemanticModel(tree); Assert.Null(model.GetDeclaredSymbol(node)); } [Fact, WorkItem(1733, "https://github.com/dotnet/roslyn/issues/1733")] public void MissingBaseType() { var source1 = @" namespace System { public class Object { } public class ValueType {} public struct Void { } public struct Boolean { } public struct Int32 { } } "; var comp1 = CreateEmptyCompilation(source1, options: TestOptions.DebugDll, assemblyName: "MissingBaseType1"); comp1.VerifyDiagnostics(); var source2 = @" public class Enumerable { public Enumerator GetEnumerator() { return default(Enumerator); } } public struct Enumerator { public int Current { get { return 0; } } public bool MoveNext() { return false; } }"; var comp2 = CreateEmptyCompilation(source2, new[] { comp1.ToMetadataReference() }, options: TestOptions.DebugDll); comp2.VerifyDiagnostics(); var source3 = @" namespace System { public class Object { } public class ValueType {} public struct Void { } public struct Boolean { } public struct Int32 { } } "; var comp3 = CreateEmptyCompilation(source3, options: TestOptions.DebugDll, assemblyName: "MissingBaseType2"); comp3.VerifyDiagnostics(); var source4 = @" class Program { static void Main() { foreach (var x in new Enumerable()) { } } }"; var comp4 = CreateEmptyCompilation(source4, new[] { comp2.ToMetadataReference(), comp3.ToMetadataReference() }); comp4.VerifyDiagnostics( // (6,9): error CS0012: The type 'ValueType' is defined in an assembly that is not referenced. You must add a reference to assembly 'MissingBaseType1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // foreach (var x in new Enumerable()) Diagnostic(ErrorCode.ERR_NoTypeDef, @"foreach (var x in new Enumerable()) { }").WithArguments("System.ValueType", "MissingBaseType1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 9) ); } [Fact] [WorkItem(26585, "https://github.com/dotnet/roslyn/issues/26585")] public void ForEachIteratorWithCurrentRefKind_Async_Ref() { CreateCompilation(@" using System.Threading.Tasks; class E { public class Enumerator { public ref int Current => throw null; public bool MoveNext() => throw null; } public Enumerator GetEnumerator() => new Enumerator(); } class C { public async static Task Test() { await Task.CompletedTask; foreach (ref int x in new E()) { System.Console.Write(x); } } }").VerifyDiagnostics( // (20,26): error CS8177: Async methods cannot have by-reference locals // foreach (ref int x in new E()) Diagnostic(ErrorCode.ERR_BadAsyncLocalType, "x").WithLocation(20, 26)); } [Fact] [WorkItem(26585, "https://github.com/dotnet/roslyn/issues/26585")] public void ForEachIteratorWithCurrentRefKind_Async_RefReadonly() { CreateCompilation(@" using System.Threading.Tasks; class E { public class Enumerator { public ref readonly int Current => throw null; public bool MoveNext() => throw null; } public Enumerator GetEnumerator() => new Enumerator(); } class C { public async static Task Test() { await Task.CompletedTask; foreach (ref readonly int x in new E()) { System.Console.Write(x); } } }").VerifyDiagnostics( // (20,35): error CS8177: Async methods cannot have by-reference locals // foreach (ref readonly int x in new E()) Diagnostic(ErrorCode.ERR_BadAsyncLocalType, "x").WithLocation(20, 35)); } [Fact] [WorkItem(26585, "https://github.com/dotnet/roslyn/issues/26585")] public void ForEachIteratorWithCurrentRefKind_Iterator_Ref() { CreateCompilation(@" using System.Collections.Generic; class E { public class Enumerator { public ref int Current => throw null; public bool MoveNext() => throw null; } public Enumerator GetEnumerator() => new Enumerator(); } class C { public static IEnumerable<int> Test() { foreach (ref int x in new E()) { yield return x; } } }").VerifyDiagnostics( // (18,26): error CS8176: Iterators cannot have by-reference locals // foreach (ref int x in new E()) Diagnostic(ErrorCode.ERR_BadIteratorLocalType, "x").WithLocation(18, 26)); } [Fact] [WorkItem(26585, "https://github.com/dotnet/roslyn/issues/26585")] public void ForEachIteratorWithCurrentRefKind_Iterator_RefReadonly() { CreateCompilation(@" using System.Collections.Generic; class E { public class Enumerator { public ref readonly int Current => throw null; public bool MoveNext() => throw null; } public Enumerator GetEnumerator() => new Enumerator(); } class C { public static IEnumerable<int> Test() { foreach (ref readonly int x in new E()) { yield return x; } } }").VerifyDiagnostics( // (18,35): error CS8176: Iterators cannot have by-reference locals // foreach (ref readonly int x in new E()) Diagnostic(ErrorCode.ERR_BadIteratorLocalType, "x").WithLocation(18, 35)); } [Fact] [WorkItem(30016, "https://github.com/dotnet/roslyn/issues/30016")] public void ForEachIteratorWithCurrentRefKind_DontPassFieldByValue() { var source = @" using System; struct S1 { public int A; } class C { public static void Main() { Span<S1> items = new Span<S1>(new S1[1]); foreach (ref var t in items) t.A++; Console.WriteLine(items[0].A); } }"; var comp = CreateCompilationWithMscorlibAndSpan(source, options: TestOptions.ReleaseDebugExe).VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "1"); } [WorkItem(32334, "https://github.com/dotnet/roslyn/issues/32334")] [Fact] public void SuppressForEachMissingMemberErrorOnErrorType() { CreateCompilation(@" using System; using System.Collections.Generic; class C { void Goo() { var nonsense = Nonsense; //Should not have error foreach(var item in nonsense) {} var nonsense2 = new Nonsense(); //Should not have error foreach(var item in nonsense2) {} var lazyNonsense = default(Lazy<Nonsense>); //Should have error foreach(var item in lazyNonsense) {} var listNonsense = new List<Nonsense>(); //Should not have error foreach(var item in listNonsense) {} var nonsenseArray = new Nonsense[0]; //Should not have error foreach(var item in nonsenseArray) {} var stringNonsense = new String.Nonsense(); //Should not have error foreach(var item in stringNonsense) {} var nonsenseString = new Nonsense.String(); //Should not have error foreach(var item in nonsenseString) {} Nonsense? nullableNonsense = default; //Should have error foreach(var item in nullableNonsense) {} var nonsenseTuple = (new Nonsense(), 42); //Should have error foreach(var item in nonsenseTuple) {} } } ").VerifyDiagnostics( // (9,24): error CS0103: The name 'Nonsense' does not exist in the current context // var nonsense = Nonsense; Diagnostic(ErrorCode.ERR_NameNotInContext, "Nonsense").WithArguments("Nonsense").WithLocation(9, 24), // (13,29): error CS0246: The type or namespace name 'Nonsense' could not be found (are you missing a using directive or an assembly reference?) // var nonsense2 = new Nonsense(); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Nonsense").WithArguments("Nonsense").WithLocation(13, 29), // (17,41): error CS0246: The type or namespace name 'Nonsense' could not be found (are you missing a using directive or an assembly reference?) // var lazyNonsense = default(Lazy<Nonsense>); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Nonsense").WithArguments("Nonsense").WithLocation(17, 41), // (19,29): error CS1579: foreach statement cannot operate on variables of type 'Lazy<Nonsense>' because 'Lazy<Nonsense>' does not contain a public instance or extension definition for 'GetEnumerator' // foreach(var item in lazyNonsense) {} Diagnostic(ErrorCode.ERR_ForEachMissingMember, "lazyNonsense").WithArguments("System.Lazy<Nonsense>", "GetEnumerator").WithLocation(19, 29), // (21,37): error CS0246: The type or namespace name 'Nonsense' could not be found (are you missing a using directive or an assembly reference?) // var listNonsense = new List<Nonsense>(); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Nonsense").WithArguments("Nonsense").WithLocation(21, 37), // (25,33): error CS0246: The type or namespace name 'Nonsense' could not be found (are you missing a using directive or an assembly reference?) // var nonsenseArray = new Nonsense[0]; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Nonsense").WithArguments("Nonsense").WithLocation(25, 33), // (29,41): error CS0426: The type name 'Nonsense' does not exist in the type 'string' // var stringNonsense = new String.Nonsense(); Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, "Nonsense").WithArguments("Nonsense", "string").WithLocation(29, 41), // (33,34): error CS0246: The type or namespace name 'Nonsense' could not be found (are you missing a using directive or an assembly reference?) // var nonsenseString = new Nonsense.String(); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Nonsense").WithArguments("Nonsense").WithLocation(33, 34), // (37,9): error CS0246: The type or namespace name 'Nonsense' could not be found (are you missing a using directive or an assembly reference?) // Nonsense? nullableNonsense = default; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Nonsense").WithArguments("Nonsense").WithLocation(37, 9), // (39,29): error CS1579: foreach statement cannot operate on variables of type 'Nonsense?' because 'Nonsense?' does not contain a public instance or extension definition for 'GetEnumerator' // foreach(var item in nullableNonsense) {} Diagnostic(ErrorCode.ERR_ForEachMissingMember, "nullableNonsense").WithArguments("Nonsense?", "GetEnumerator").WithLocation(39, 29), // (41,34): error CS0246: The type or namespace name 'Nonsense' could not be found (are you missing a using directive or an assembly reference?) // var nonsenseTuple = (new Nonsense(), 42); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Nonsense").WithArguments("Nonsense").WithLocation(41, 34), // (43,29): error CS1579: foreach statement cannot operate on variables of type '(Nonsense, int)' because '(Nonsense, int)' does not contain a public instance or extension definition for 'GetEnumerator' // foreach(var item in nonsenseTuple) {} Diagnostic(ErrorCode.ERR_ForEachMissingMember, "nonsenseTuple").WithArguments("(Nonsense, int)", "GetEnumerator").WithLocation(43, 29)); } } }
-1
dotnet/roslyn
55,409
Use FixedSize API
tmat
2021-08-04T19:30:40Z
2021-08-04T21:53:46Z
e0112742bff208dd0546de45e36f7b52058a45a3
c90bf0ec986010051662c8e1fbc872c2fd86bc4e
Use FixedSize API.
./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_ITypeOfExpression.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_ITypeOfExpression : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestTypeOfExpression() { string source = @" using System; class C { void M(Type t) { t = /*<bind>*/typeof(int)/*</bind>*/; } } "; string expectedOperationTree = @" ITypeOfOperation (OperationKind.TypeOf, Type: System.Type) (Syntax: 'typeof(int)') TypeOperand: System.Int32 "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<TypeOfExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestTypeOfExpression_NonPrimitiveTypeArgument() { string source = @" using System; class C { void M(Type t) { t = /*<bind>*/typeof(C)/*</bind>*/; } } "; string expectedOperationTree = @" ITypeOfOperation (OperationKind.TypeOf, Type: System.Type) (Syntax: 'typeof(C)') TypeOperand: C "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<TypeOfExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestTypeOfExpression_ErrorTypeArgument() { string source = @" using System; class C { void M(Type t) { t = /*<bind>*/typeof(UndefinedType)/*</bind>*/; } } "; string expectedOperationTree = @" ITypeOfOperation (OperationKind.TypeOf, Type: System.Type, IsInvalid) (Syntax: 'typeof(UndefinedType)') TypeOperand: UndefinedType "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0246: The type or namespace name 'UndefinedType' could not be found (are you missing a using directive or an assembly reference?) // t = /*<bind>*/typeof(UndefinedType)/*</bind>*/; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UndefinedType").WithArguments("UndefinedType").WithLocation(8, 30) }; VerifyOperationTreeAndDiagnosticsForTest<TypeOfExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestTypeOfExpression_IdentifierArgument() { string source = @" using System; class C { void M(Type t) { t = /*<bind>*/typeof(t)/*</bind>*/; } } "; string expectedOperationTree = @" ITypeOfOperation (OperationKind.TypeOf, Type: System.Type, IsInvalid) (Syntax: 'typeof(t)') TypeOperand: t "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0118: 't' is a variable but is used like a type // t = /*<bind>*/typeof(t)/*</bind>*/; Diagnostic(ErrorCode.ERR_BadSKknown, "t").WithArguments("t", "variable", "type").WithLocation(8, 30) }; VerifyOperationTreeAndDiagnosticsForTest<TypeOfExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestTypeOfExpression_ExpressionArgument() { string source = @" using System; class C { void M(Type t) { t = /*<bind>*/typeof(M2()/*</bind>*/); } Type M2() => null; } "; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'typeof(M2()') Children(1): ITypeOfOperation (OperationKind.TypeOf, Type: System.Type, IsInvalid) (Syntax: 'typeof(M2') TypeOperand: M2 "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1026: ) expected // t = /*<bind>*/typeof(M2()/*</bind>*/); Diagnostic(ErrorCode.ERR_CloseParenExpected, "(").WithLocation(8, 32), // CS1002: ; expected // t = /*<bind>*/typeof(M2()/*</bind>*/); Diagnostic(ErrorCode.ERR_SemicolonExpected, ")").WithLocation(8, 45), // CS1513: } expected // t = /*<bind>*/typeof(M2()/*</bind>*/); Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(8, 45), // CS0246: The type or namespace name 'M2' could not be found (are you missing a using directive or an assembly reference?) // t = /*<bind>*/typeof(M2()/*</bind>*/); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "M2").WithArguments("M2").WithLocation(8, 30) }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestTypeOfExpression_MissingArgument() { string source = @" using System; class C { void M(Type t) { t = /*<bind>*/typeof()/*</bind>*/; } } "; string expectedOperationTree = @" ITypeOfOperation (OperationKind.TypeOf, Type: System.Type, IsInvalid) (Syntax: 'typeof()') TypeOperand: ? "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1031: Type expected // t = /*<bind>*/typeof()/*</bind>*/; Diagnostic(ErrorCode.ERR_TypeExpected, ")").WithLocation(8, 30) }; VerifyOperationTreeAndDiagnosticsForTest<TypeOfExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TypeOfFlow_01() { string source = @" class C { void M(System.Type t) /*<bind>*/{ t = typeof(bool); }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 't = typeof(bool);') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Type) (Syntax: 't = typeof(bool)') Left: IParameterReferenceOperation: t (OperationKind.ParameterReference, Type: System.Type) (Syntax: 't') Right: ITypeOfOperation (OperationKind.TypeOf, Type: System.Type) (Syntax: 'typeof(bool)') TypeOperand: System.Boolean Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_ITypeOfExpression : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestTypeOfExpression() { string source = @" using System; class C { void M(Type t) { t = /*<bind>*/typeof(int)/*</bind>*/; } } "; string expectedOperationTree = @" ITypeOfOperation (OperationKind.TypeOf, Type: System.Type) (Syntax: 'typeof(int)') TypeOperand: System.Int32 "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<TypeOfExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestTypeOfExpression_NonPrimitiveTypeArgument() { string source = @" using System; class C { void M(Type t) { t = /*<bind>*/typeof(C)/*</bind>*/; } } "; string expectedOperationTree = @" ITypeOfOperation (OperationKind.TypeOf, Type: System.Type) (Syntax: 'typeof(C)') TypeOperand: C "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<TypeOfExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestTypeOfExpression_ErrorTypeArgument() { string source = @" using System; class C { void M(Type t) { t = /*<bind>*/typeof(UndefinedType)/*</bind>*/; } } "; string expectedOperationTree = @" ITypeOfOperation (OperationKind.TypeOf, Type: System.Type, IsInvalid) (Syntax: 'typeof(UndefinedType)') TypeOperand: UndefinedType "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0246: The type or namespace name 'UndefinedType' could not be found (are you missing a using directive or an assembly reference?) // t = /*<bind>*/typeof(UndefinedType)/*</bind>*/; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UndefinedType").WithArguments("UndefinedType").WithLocation(8, 30) }; VerifyOperationTreeAndDiagnosticsForTest<TypeOfExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestTypeOfExpression_IdentifierArgument() { string source = @" using System; class C { void M(Type t) { t = /*<bind>*/typeof(t)/*</bind>*/; } } "; string expectedOperationTree = @" ITypeOfOperation (OperationKind.TypeOf, Type: System.Type, IsInvalid) (Syntax: 'typeof(t)') TypeOperand: t "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0118: 't' is a variable but is used like a type // t = /*<bind>*/typeof(t)/*</bind>*/; Diagnostic(ErrorCode.ERR_BadSKknown, "t").WithArguments("t", "variable", "type").WithLocation(8, 30) }; VerifyOperationTreeAndDiagnosticsForTest<TypeOfExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestTypeOfExpression_ExpressionArgument() { string source = @" using System; class C { void M(Type t) { t = /*<bind>*/typeof(M2()/*</bind>*/); } Type M2() => null; } "; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'typeof(M2()') Children(1): ITypeOfOperation (OperationKind.TypeOf, Type: System.Type, IsInvalid) (Syntax: 'typeof(M2') TypeOperand: M2 "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1026: ) expected // t = /*<bind>*/typeof(M2()/*</bind>*/); Diagnostic(ErrorCode.ERR_CloseParenExpected, "(").WithLocation(8, 32), // CS1002: ; expected // t = /*<bind>*/typeof(M2()/*</bind>*/); Diagnostic(ErrorCode.ERR_SemicolonExpected, ")").WithLocation(8, 45), // CS1513: } expected // t = /*<bind>*/typeof(M2()/*</bind>*/); Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(8, 45), // CS0246: The type or namespace name 'M2' could not be found (are you missing a using directive or an assembly reference?) // t = /*<bind>*/typeof(M2()/*</bind>*/); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "M2").WithArguments("M2").WithLocation(8, 30) }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestTypeOfExpression_MissingArgument() { string source = @" using System; class C { void M(Type t) { t = /*<bind>*/typeof()/*</bind>*/; } } "; string expectedOperationTree = @" ITypeOfOperation (OperationKind.TypeOf, Type: System.Type, IsInvalid) (Syntax: 'typeof()') TypeOperand: ? "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1031: Type expected // t = /*<bind>*/typeof()/*</bind>*/; Diagnostic(ErrorCode.ERR_TypeExpected, ")").WithLocation(8, 30) }; VerifyOperationTreeAndDiagnosticsForTest<TypeOfExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TypeOfFlow_01() { string source = @" class C { void M(System.Type t) /*<bind>*/{ t = typeof(bool); }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 't = typeof(bool);') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Type) (Syntax: 't = typeof(bool)') Left: IParameterReferenceOperation: t (OperationKind.ParameterReference, Type: System.Type) (Syntax: 't') Right: ITypeOfOperation (OperationKind.TypeOf, Type: System.Type) (Syntax: 'typeof(bool)') TypeOperand: System.Boolean Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } } }
-1
dotnet/roslyn
55,409
Use FixedSize API
tmat
2021-08-04T19:30:40Z
2021-08-04T21:53:46Z
e0112742bff208dd0546de45e36f7b52058a45a3
c90bf0ec986010051662c8e1fbc872c2fd86bc4e
Use FixedSize API.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Collections/IIntervalIntrospector.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.Shared.Collections { internal interface IIntervalIntrospector<T> { int GetStart(T value); int GetLength(T value); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.Shared.Collections { internal interface IIntervalIntrospector<T> { int GetStart(T value); int GetLength(T value); } }
-1
dotnet/roslyn
55,409
Use FixedSize API
tmat
2021-08-04T19:30:40Z
2021-08-04T21:53:46Z
e0112742bff208dd0546de45e36f7b52058a45a3
c90bf0ec986010051662c8e1fbc872c2fd86bc4e
Use FixedSize API.
./src/Compilers/VisualBasic/Portable/BoundTree/BoundAnonymousTypePropertyAccess.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class BoundAnonymousTypePropertyAccess Private ReadOnly _lazyPropertySymbol As New Lazy(Of PropertySymbol)(AddressOf LazyGetProperty) Public Overrides ReadOnly Property ExpressionSymbol As Symbol Get Return Me._lazyPropertySymbol.Value End Get End Property Private Function LazyGetProperty() As PropertySymbol Return Me.Binder.GetAnonymousTypePropertySymbol(Me.PropertyIndex) 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.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class BoundAnonymousTypePropertyAccess Private ReadOnly _lazyPropertySymbol As New Lazy(Of PropertySymbol)(AddressOf LazyGetProperty) Public Overrides ReadOnly Property ExpressionSymbol As Symbol Get Return Me._lazyPropertySymbol.Value End Get End Property Private Function LazyGetProperty() As PropertySymbol Return Me.Binder.GetAnonymousTypePropertySymbol(Me.PropertyIndex) End Function End Class End Namespace
-1
dotnet/roslyn
55,409
Use FixedSize API
tmat
2021-08-04T19:30:40Z
2021-08-04T21:53:46Z
e0112742bff208dd0546de45e36f7b52058a45a3
c90bf0ec986010051662c8e1fbc872c2fd86bc4e
Use FixedSize API.
./src/Compilers/CSharp/Test/Symbol/Symbols/MethodImplementationFlagsTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Reflection; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols { public class MethodImplementationFlagsTests : CSharpTestBase { [Fact] public void TestInliningFlags() { var src = @" using System.Runtime.CompilerServices; public class C { [MethodImpl(MethodImplOptions.AggressiveInlining)] public void M_Aggressive() { } [MethodImpl(MethodImplOptions.NoInlining)] public void M_NoInlining() { } } "; Action<ModuleSymbol> validator = module => { var c = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var aggressiveInliningMethod = c.GetMember<MethodSymbol>("M_Aggressive").GetPublicSymbol(); Assert.Equal(MethodImplAttributes.AggressiveInlining, aggressiveInliningMethod.MethodImplementationFlags); var noInliningMethod = c.GetMember<MethodSymbol>("M_NoInlining").GetPublicSymbol(); Assert.Equal(MethodImplAttributes.NoInlining, noInliningMethod.MethodImplementationFlags); }; CompileAndVerify(src, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void TestOptimizationFlags() { var src = @" using System.Runtime.CompilerServices; public class C { [MethodImpl((MethodImplOptions)512)] // Aggressive optimization public void M_Aggressive() { } [MethodImpl(MethodImplOptions.NoOptimization)] public void M_NoOptimization() { } } "; Action<ModuleSymbol> validator = module => { var c = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var aggressiveOptimizationMethod = c.GetMember<MethodSymbol>("M_Aggressive").GetPublicSymbol(); #if !NET472 // MethodImplAttributes.AggressiveOptimization was introduced in .NET Core 3 Assert.Equal(MethodImplAttributes.AggressiveOptimization, aggressiveOptimizationMethod.MethodImplementationFlags); #else Assert.Equal((MethodImplAttributes)512, aggressiveOptimizationMethod.MethodImplementationFlags); #endif var noOptimizationMethod = c.GetMember<MethodSymbol>("M_NoOptimization").GetPublicSymbol(); Assert.Equal(MethodImplAttributes.NoOptimization, noOptimizationMethod.MethodImplementationFlags); }; CompileAndVerify(src, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void TestMixingOptimizationWithInliningFlags() { var src = @" using System.Runtime.CompilerServices; public class C { [MethodImpl((MethodImplOptions)512 | MethodImplOptions.NoInlining)] // aggressive optimization and no inlining public void M_AggressiveOpt_NoInlining() { } [MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)] public void M_NoOpt_NoInlining() { } [MethodImpl((MethodImplOptions)512 | MethodImplOptions.AggressiveInlining)] // aggressive optimization and aggressive inlining public void M_AggressiveOpt_AggressiveInlining() { } [MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.AggressiveInlining)] public void M_NoOpt_AggressiveInlining() { } } "; Action<ModuleSymbol> validator = module => { var c = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var aggressiveOptNoInliningMethod = c.GetMember<MethodSymbol>("M_AggressiveOpt_NoInlining").GetPublicSymbol(); #if !NET472 // MethodImplAttributes.AggressiveOptimization was introduced in .NET Core 3 Assert.Equal(MethodImplAttributes.AggressiveOptimization | MethodImplAttributes.NoInlining, aggressiveOptNoInliningMethod.MethodImplementationFlags); #else Assert.Equal((MethodImplAttributes)512 | MethodImplAttributes.NoInlining, aggressiveOptNoInliningMethod.MethodImplementationFlags); #endif var noOptNoInliningMethod = c.GetMember<MethodSymbol>("M_NoOpt_NoInlining").GetPublicSymbol(); Assert.Equal(MethodImplAttributes.NoOptimization | MethodImplAttributes.NoInlining, noOptNoInliningMethod.MethodImplementationFlags); var aggressiveOptAggressiveInliningMethod = c.GetMember<MethodSymbol>("M_AggressiveOpt_AggressiveInlining").GetPublicSymbol(); #if !NET472 Assert.Equal(MethodImplAttributes.AggressiveOptimization | MethodImplAttributes.AggressiveInlining, aggressiveOptAggressiveInliningMethod.MethodImplementationFlags); #else Assert.Equal((MethodImplAttributes)512 | MethodImplAttributes.AggressiveInlining, aggressiveOptAggressiveInliningMethod.MethodImplementationFlags); #endif var noOptAggressiveInliningMethod = c.GetMember<MethodSymbol>("M_NoOpt_AggressiveInlining").GetPublicSymbol(); Assert.Equal(MethodImplAttributes.NoOptimization | MethodImplAttributes.AggressiveInlining, noOptAggressiveInliningMethod.MethodImplementationFlags); }; CompileAndVerify(src, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void TestPreserveSigAndRuntimeFlags() { var src = @" using System.Runtime.CompilerServices; public class C { [MethodImpl(MethodImplOptions.PreserveSig, MethodCodeType = MethodCodeType.Runtime)] public void M() { } } "; Action<ModuleSymbol> validator = module => { var c = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var method = c.GetMember<MethodSymbol>("M").GetPublicSymbol(); Assert.Equal(MethodImplAttributes.PreserveSig | MethodImplAttributes.Runtime, method.MethodImplementationFlags); }; CompileAndVerify(src, sourceSymbolValidator: validator, symbolValidator: validator, verify: Verification.Skipped); } [Fact] public void TestNativeFlag() { var src = @" using System.Runtime.CompilerServices; public class C { [MethodImpl(MethodCodeType = MethodCodeType.Native)] public extern void M(); } "; Action<ModuleSymbol> validator = module => { var c = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var method = c.GetMember<MethodSymbol>("M").GetPublicSymbol(); Assert.Equal(MethodImplAttributes.Native, method.MethodImplementationFlags); }; CompileAndVerify(src, sourceSymbolValidator: validator, symbolValidator: validator, verify: Verification.Skipped); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Reflection; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols { public class MethodImplementationFlagsTests : CSharpTestBase { [Fact] public void TestInliningFlags() { var src = @" using System.Runtime.CompilerServices; public class C { [MethodImpl(MethodImplOptions.AggressiveInlining)] public void M_Aggressive() { } [MethodImpl(MethodImplOptions.NoInlining)] public void M_NoInlining() { } } "; Action<ModuleSymbol> validator = module => { var c = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var aggressiveInliningMethod = c.GetMember<MethodSymbol>("M_Aggressive").GetPublicSymbol(); Assert.Equal(MethodImplAttributes.AggressiveInlining, aggressiveInliningMethod.MethodImplementationFlags); var noInliningMethod = c.GetMember<MethodSymbol>("M_NoInlining").GetPublicSymbol(); Assert.Equal(MethodImplAttributes.NoInlining, noInliningMethod.MethodImplementationFlags); }; CompileAndVerify(src, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void TestOptimizationFlags() { var src = @" using System.Runtime.CompilerServices; public class C { [MethodImpl((MethodImplOptions)512)] // Aggressive optimization public void M_Aggressive() { } [MethodImpl(MethodImplOptions.NoOptimization)] public void M_NoOptimization() { } } "; Action<ModuleSymbol> validator = module => { var c = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var aggressiveOptimizationMethod = c.GetMember<MethodSymbol>("M_Aggressive").GetPublicSymbol(); #if !NET472 // MethodImplAttributes.AggressiveOptimization was introduced in .NET Core 3 Assert.Equal(MethodImplAttributes.AggressiveOptimization, aggressiveOptimizationMethod.MethodImplementationFlags); #else Assert.Equal((MethodImplAttributes)512, aggressiveOptimizationMethod.MethodImplementationFlags); #endif var noOptimizationMethod = c.GetMember<MethodSymbol>("M_NoOptimization").GetPublicSymbol(); Assert.Equal(MethodImplAttributes.NoOptimization, noOptimizationMethod.MethodImplementationFlags); }; CompileAndVerify(src, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void TestMixingOptimizationWithInliningFlags() { var src = @" using System.Runtime.CompilerServices; public class C { [MethodImpl((MethodImplOptions)512 | MethodImplOptions.NoInlining)] // aggressive optimization and no inlining public void M_AggressiveOpt_NoInlining() { } [MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)] public void M_NoOpt_NoInlining() { } [MethodImpl((MethodImplOptions)512 | MethodImplOptions.AggressiveInlining)] // aggressive optimization and aggressive inlining public void M_AggressiveOpt_AggressiveInlining() { } [MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.AggressiveInlining)] public void M_NoOpt_AggressiveInlining() { } } "; Action<ModuleSymbol> validator = module => { var c = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var aggressiveOptNoInliningMethod = c.GetMember<MethodSymbol>("M_AggressiveOpt_NoInlining").GetPublicSymbol(); #if !NET472 // MethodImplAttributes.AggressiveOptimization was introduced in .NET Core 3 Assert.Equal(MethodImplAttributes.AggressiveOptimization | MethodImplAttributes.NoInlining, aggressiveOptNoInliningMethod.MethodImplementationFlags); #else Assert.Equal((MethodImplAttributes)512 | MethodImplAttributes.NoInlining, aggressiveOptNoInliningMethod.MethodImplementationFlags); #endif var noOptNoInliningMethod = c.GetMember<MethodSymbol>("M_NoOpt_NoInlining").GetPublicSymbol(); Assert.Equal(MethodImplAttributes.NoOptimization | MethodImplAttributes.NoInlining, noOptNoInliningMethod.MethodImplementationFlags); var aggressiveOptAggressiveInliningMethod = c.GetMember<MethodSymbol>("M_AggressiveOpt_AggressiveInlining").GetPublicSymbol(); #if !NET472 Assert.Equal(MethodImplAttributes.AggressiveOptimization | MethodImplAttributes.AggressiveInlining, aggressiveOptAggressiveInliningMethod.MethodImplementationFlags); #else Assert.Equal((MethodImplAttributes)512 | MethodImplAttributes.AggressiveInlining, aggressiveOptAggressiveInliningMethod.MethodImplementationFlags); #endif var noOptAggressiveInliningMethod = c.GetMember<MethodSymbol>("M_NoOpt_AggressiveInlining").GetPublicSymbol(); Assert.Equal(MethodImplAttributes.NoOptimization | MethodImplAttributes.AggressiveInlining, noOptAggressiveInliningMethod.MethodImplementationFlags); }; CompileAndVerify(src, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void TestPreserveSigAndRuntimeFlags() { var src = @" using System.Runtime.CompilerServices; public class C { [MethodImpl(MethodImplOptions.PreserveSig, MethodCodeType = MethodCodeType.Runtime)] public void M() { } } "; Action<ModuleSymbol> validator = module => { var c = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var method = c.GetMember<MethodSymbol>("M").GetPublicSymbol(); Assert.Equal(MethodImplAttributes.PreserveSig | MethodImplAttributes.Runtime, method.MethodImplementationFlags); }; CompileAndVerify(src, sourceSymbolValidator: validator, symbolValidator: validator, verify: Verification.Skipped); } [Fact] public void TestNativeFlag() { var src = @" using System.Runtime.CompilerServices; public class C { [MethodImpl(MethodCodeType = MethodCodeType.Native)] public extern void M(); } "; Action<ModuleSymbol> validator = module => { var c = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var method = c.GetMember<MethodSymbol>("M").GetPublicSymbol(); Assert.Equal(MethodImplAttributes.Native, method.MethodImplementationFlags); }; CompileAndVerify(src, sourceSymbolValidator: validator, symbolValidator: validator, verify: Verification.Skipped); } } }
-1
dotnet/roslyn
55,409
Use FixedSize API
tmat
2021-08-04T19:30:40Z
2021-08-04T21:53:46Z
e0112742bff208dd0546de45e36f7b52058a45a3
c90bf0ec986010051662c8e1fbc872c2fd86bc4e
Use FixedSize API.
./src/EditorFeatures/Text/ExternalAccess/VSTypeScript/Api/VSTypeScriptTextBufferExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api { internal static class VSTypeScriptTextBufferExtensions { public static SourceTextContainer AsTextContainer(this ITextBuffer buffer) => Text.Extensions.TextBufferContainer.From(buffer); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api { internal static class VSTypeScriptTextBufferExtensions { public static SourceTextContainer AsTextContainer(this ITextBuffer buffer) => Text.Extensions.TextBufferContainer.From(buffer); } }
-1
dotnet/roslyn
55,409
Use FixedSize API
tmat
2021-08-04T19:30:40Z
2021-08-04T21:53:46Z
e0112742bff208dd0546de45e36f7b52058a45a3
c90bf0ec986010051662c8e1fbc872c2fd86bc4e
Use FixedSize API.
./src/Compilers/VisualBasic/Test/Emit/CodeGen/AnonymousTypesCodeGenTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.IO Imports System.Threading.Tasks Imports System.Xml.Linq Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class AnonymousTypesCodeGenTests Inherits BasicTestBase <Fact()> Public Sub TestSimpleAnonymousType() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) Dim a As Integer = (New With {.a = 1, .b="text"}).a Dim b As String = (New With {.a = 1, .b="text"}).B Console.WriteLine(String.Format(".a={0}; .b={1}", a, b)) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ .a=1; .b=text ]]>). VerifyIL("VB$AnonymousType_0(Of T0, T1).get_a()", <![CDATA[ { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld "VB$AnonymousType_0(Of T0, T1).$a As T0" IL_0006: ret } ]]>). VerifyIL("VB$AnonymousType_0(Of T0, T1).set_a(T0)", <![CDATA[ { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld "VB$AnonymousType_0(Of T0, T1).$a As T0" IL_0007: ret } ]]>). VerifyIL("VB$AnonymousType_0(Of T0, T1).get_b()", <![CDATA[ { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld "VB$AnonymousType_0(Of T0, T1).$b As T1" IL_0006: ret } ]]>). VerifyIL("VB$AnonymousType_0(Of T0, T1).set_b(T1)", <![CDATA[ { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld "VB$AnonymousType_0(Of T0, T1).$b As T1" IL_0007: ret } ]]>). VerifyIL("VB$AnonymousType_0(Of T0, T1)..ctor(T0, T1)", <![CDATA[ { // Code size 21 (0x15) .maxstack 2 IL_0000: ldarg.0 IL_0001: call "Sub Object..ctor()" IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld "VB$AnonymousType_0(Of T0, T1).$a As T0" IL_000d: ldarg.0 IL_000e: ldarg.2 IL_000f: stfld "VB$AnonymousType_0(Of T0, T1).$b As T1" IL_0014: ret } ]]>) End Sub <Fact> Public Sub AnonymousTypeSymbol_Simple_Threadsafety() Dim source = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim at1 = New With {.a = 1, .b = 2} Dim at2 = New With {.a = 1, .b = 2, .c = 3} Dim at3 = New With {.a = 1, .b = 2, .c = 3, .d = 4} Dim at4 = New With {.a = 1, .b = 2, .c = 3, .d = 4, .e = 5} Dim at5 = New With {.a = 1, .b = 2, .c = 3, .d = 4, .e = 5, .f = 6} Dim at6 = New With {.a = 1, .b = 2, .c = 3, .d = 4, .e = 5, .f = 6, .g = 7} Dim at7 = New With {.a = 1, .b = 2, .c = 3, .d = 4, .e = 5, .f = 6, .g = 7, .h = 8} Dim at8 = New With {.a = 1, .b = 2, .c = 3, .d = 4, .e = 5, .f = 6, .g = 7, .h = 8, .j = 9} Dim at9 = New With {.a = 1, .b = 2, .c = 3, .d = 4, .e = 5, .f = 6, .g = 7, .h = 8, .j = 9, .k = 10} Dim at11 = New With {.aa = 1, .b = 2} Dim at12 = New With {.aa = 1, .b = 2, .c = 3} Dim at13 = New With {.aa = 1, .b = 2, .c = 3, .d = 4} Dim at14 = New With {.aa = 1, .b = 2, .c = 3, .d = 4, .e = 5} Dim at15 = New With {.aa = 1, .b = 2, .c = 3, .d = 4, .e = 5, .f = 6} Dim at16 = New With {.aa = 1, .b = 2, .c = 3, .d = 4, .e = 5, .f = 6, .g = 7} Dim at17 = New With {.aa = 1, .b = 2, .c = 3, .d = 4, .e = 5, .f = 6, .g = 7, .h = 8} Dim at18 = New With {.aa = 1, .b = 2, .c = 3, .d = 4, .e = 5, .f = 6, .g = 7, .h = 8, .j = 9} Dim at19 = New With {.aa = 1, .b = 2, .c = 3, .d = 4, .e = 5, .f = 6, .g = 7, .h = 8, .j = 9, .k = 10} Dim at21 = New With {.ba = 1, .b = 2} Dim at22 = New With {.ba = 1, .b = 2, .c = 3} Dim at23 = New With {.ba = 1, .b = 2, .c = 3, .d = 4} Dim at24 = New With {.ba = 1, .b = 2, .c = 3, .d = 4, .e = 5} Dim at25 = New With {.ba = 1, .b = 2, .c = 3, .d = 4, .e = 5, .f = 6} Dim at26 = New With {.ba = 1, .b = 2, .c = 3, .d = 4, .e = 5, .f = 6, .g = 7} Dim at27 = New With {.ba = 1, .b = 2, .c = 3, .d = 4, .e = 5, .f = 6, .g = 7, .h = 8} Dim at28 = New With {.ba = 1, .b = 2, .c = 3, .d = 4, .e = 5, .f = 6, .g = 7, .h = 8, .j = 9} Dim at29 = New With {.ba = 1, .b = 2, .c = 3, .d = 4, .e = 5, .f = 6, .g = 7, .h = 8, .j = 9, .k = 10} Dim at31 = New With {.ca = 1, .b = 2} Dim at32 = New With {.ca = 1, .b = 2, .c = 3} Dim at33 = New With {.ca = 1, .b = 2, .c = 3, .d = 4} Dim at34 = New With {.ca = 1, .b = 2, .c = 3, .d = 4, .e = 5} Dim at35 = New With {.ca = 1, .b = 2, .c = 3, .d = 4, .e = 5, .f = 6} Dim at36 = New With {.ca = 1, .b = 2, .c = 3, .d = 4, .e = 5, .f = 6, .g = 7} Dim at37 = New With {.ca = 1, .b = 2, .c = 3, .d = 4, .e = 5, .f = 6, .g = 7, .h = 8} Dim at38 = New With {.ca = 1, .b = 2, .c = 3, .d = 4, .e = 5, .f = 6, .g = 7, .h = 8, .j = 9} Dim at39 = New With {.ca = 1, .b = 2, .c = 3, .d = 4, .e = 5, .f = 6, .g = 7, .h = 8, .j = 9, .k = 10} Dim at41 = New With {.da = 1, .b = 2} Dim at42 = New With {.da = 1, .b = 2, .c = 3} Dim at43 = New With {.da = 1, .b = 2, .c = 3, .d = 4} Dim at44 = New With {.da = 1, .b = 2, .c = 3, .d = 4, .e = 5} Dim at45 = New With {.da = 1, .b = 2, .c = 3, .d = 4, .e = 5, .f = 6} Dim at46 = New With {.da = 1, .b = 2, .c = 3, .d = 4, .e = 5, .f = 6, .g = 7} Dim at47 = New With {.da = 1, .b = 2, .c = 3, .d = 4, .e = 5, .f = 6, .g = 7, .h = 8} Dim at48 = New With {.da = 1, .b = 2, .c = 3, .d = 4, .e = 5, .f = 6, .g = 7, .h = 8, .j = 9} Dim at49 = New With {.da = 1, .b = 2, .c = 3, .d = 4, .e = 5, .f = 6, .g = 7, .h = 8, .j = 9, .k = 10} End Sub End Module </file> </compilation> For i = 0 To 100 Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source) Dim tasks(10) As Task For jj = 0 To tasks.Length - 1 Dim j = jj tasks(j) = Task.Run(Sub() Dim stream = New MemoryStream() Dim result = compilation.Emit(stream, options:=New EmitOptions(metadataOnly:=j Mod 2 = 0)) result.Diagnostics.Verify() End Sub) Next ' this should Not fail. if you ever see a NRE Or some kind of crash here enter a bug. ' it may be reproducing just once in a while, in Release only... ' it Is still a bug. Task.WaitAll(tasks) Next End Sub <WorkItem(544243, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544243")> <Fact()> Public Sub TestAnonymousTypeInUnreachableCode_If1() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Test Sub Main(args() As String) If False Then Dim dummy As Object = New With {.a = 1} End If Console.WriteLine(If(GetType(Test).Assembly.GetType("VB$AnonymousType_0`1"), "Type Not Found")) End Sub End Module </file> </compilation>, expectedOutput:="VB$AnonymousType_0`1[T0]") End Sub <WorkItem(544243, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544243")> <Fact()> Public Sub TestAnonymousTypeInUnreachableCode_If2() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Test Sub Main(args() As String) If False Then Dim dummy = New With {.a = 1} End If Console.WriteLine(If(GetType(Test).Assembly.GetType("VB$AnonymousType_0`1"), "Type Not Found")) End Sub End Module </file> </compilation>, expectedOutput:="VB$AnonymousType_0`1[T0]") End Sub <WorkItem(544243, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544243")> <Fact()> Public Sub TestAnonymousTypeInUnreachableCode_If3() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Test Sub Main(args() As String) If False Then Dim dummy = New With {.a = New With {.b = 1}} End If Console.WriteLine(If(GetType(Test).Assembly.GetType("VB$AnonymousType_0`1"), "Type Not Found")) End Sub End Module </file> </compilation>, expectedOutput:="VB$AnonymousType_0`1[T0]") End Sub <WorkItem(544243, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544243")> <Fact()> Public Sub TestAnonymousTypeInUnreachableCode_Conditional1() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Test Sub Main(args() As String) Dim dummy As Object = If(False, New With {.a = 1}, Nothing) Console.WriteLine(If(GetType(Test).Assembly.GetType("VB$AnonymousType_0`1"), "Type Not Found")) End Sub End Module </file> </compilation>, expectedOutput:="VB$AnonymousType_0`1[T0]") End Sub <WorkItem(544243, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544243")> <Fact()> Public Sub TestAnonymousTypeInUnreachableCode_Conditional2() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Test Sub Main(args() As String) Dim dummy = If(False, New With {.a = 1}, Nothing) Console.WriteLine(If(GetType(Test).Assembly.GetType("VB$AnonymousType_0`1"), "Type Not Found")) End Sub End Module </file> </compilation>, expectedOutput:="VB$AnonymousType_0`1[T0]") End Sub <WorkItem(544243, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544243")> <Fact()> Public Sub TestAnonymousTypeInUnreachableCode_Conditional3() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Test Sub Main(args() As String) Dim dummy = If(False, New With {.a = New With {.b = 1}}, Nothing) Console.WriteLine(If(GetType(Test).Assembly.GetType("VB$AnonymousType_0`1"), "Type Not Found")) End Sub End Module </file> </compilation>, expectedOutput:="VB$AnonymousType_0`1[T0]") End Sub <WorkItem(544243, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544243")> <Fact()> Public Sub TestAnonymousTypeInUnreachableCode_Conditional4() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Test Sub Main(args() As String) Dim dummy = If("abc", New With {.a = New With {.b = 1}}) Console.WriteLine(If(GetType(Test).Assembly.GetType("VB$AnonymousType_0`1"), "Type Not Found")) End Sub End Module </file> </compilation>, expectedOutput:="VB$AnonymousType_0`1[T0]") End Sub <WorkItem(544243, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544243")> <Fact()> Public Sub TestAnonymousTypeInUnreachableCode_Conditional5() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Test Sub Main(args() As String) Dim dummy = If("abc", Sub() Dim a = New With {.a = New With {.b = 1}} End Sub) Console.WriteLine(If(GetType(Test).Assembly.GetType("VB$AnonymousType_0`1"), "Type Not Found")) End Sub End Module </file> </compilation>, expectedOutput:="VB$AnonymousType_0`1[T0]") End Sub <WorkItem(544243, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544243")> <Fact()> Public Sub TestAnonymousTypeInUnreachableCode_Conditional_CollInitializer1() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Test Sub Main(args() As String) Dim dummy As Object = If(False, { New With {.a = 1} }, Nothing) Console.WriteLine(If(GetType(Test).Assembly.GetType("VB$AnonymousType_0`1"), "Type Not Found")) End Sub End Module </file> </compilation>, expectedOutput:="VB$AnonymousType_0`1[T0]") End Sub <WorkItem(544243, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544243")> <Fact()> Public Sub TestAnonymousTypeInUnreachableCode_Conditional_CollInitializer2() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Test Sub Main(args() As String) Dim dummy = If(False, { New With {.a = 1} }, Nothing) Console.WriteLine(If(GetType(Test).Assembly.GetType("VB$AnonymousType_0`1"), "Type Not Found")) End Sub End Module </file> </compilation>, expectedOutput:="VB$AnonymousType_0`1[T0]") End Sub <Fact()> Public Sub TestAnonymousType_ToString() ' test AnonymousType_ToString() itself Dim currCulture = System.Threading.Thread.CurrentThread.CurrentCulture System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture Try CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) Console.WriteLine((New With {Key .a = 1, .b="text", Key .c=123.456}).ToString()) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ { a = 1, b = text, c = 123.456 } ]]>). VerifyIL("VB$AnonymousType_0(Of T0, T1, T2).ToString()", <![CDATA[ { // Code size 60 (0x3c) .maxstack 6 IL_0000: ldnull IL_0001: ldstr "{{ a = {0}, b = {1}, c = {2} }}" IL_0006: ldc.i4.3 IL_0007: newarr "Object" IL_000c: dup IL_000d: ldc.i4.0 IL_000e: ldarg.0 IL_000f: ldfld "VB$AnonymousType_0(Of T0, T1, T2).$a As T0" IL_0014: box "T0" IL_0019: stelem.ref IL_001a: dup IL_001b: ldc.i4.1 IL_001c: ldarg.0 IL_001d: ldfld "VB$AnonymousType_0(Of T0, T1, T2).$b As T1" IL_0022: box "T1" IL_0027: stelem.ref IL_0028: dup IL_0029: ldc.i4.2 IL_002a: ldarg.0 IL_002b: ldfld "VB$AnonymousType_0(Of T0, T1, T2).$c As T2" IL_0030: box "T2" IL_0035: stelem.ref IL_0036: call "Function String.Format(System.IFormatProvider, String, ParamArray Object()) As String" IL_003b: ret } ]]>) Catch ex As Exception Assert.Null(ex) Finally System.Threading.Thread.CurrentThread.CurrentCulture = currCulture End Try End Sub <Fact()> Public Sub TestAnonymousType_IEquatable_Equals() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Structure S Public X As Integer Public Y As Integer Public Sub New(_x As Integer, _y As Integer) Me.X = _x Me.Y = _y End Sub Public Sub New(_x As Integer) Me.X = 0 Me.Y = 0 End Sub End Structure Sub Main(args As String()) Console.WriteLine((New With {Key .a = 1, .b="text", Key .c=New S(1,2)}).Equals(New With {Key .a = 1, .b="text", Key .c=New S(1,2)})) Console.WriteLine((New With {Key .a = 1, .b="text", Key .c=New S(1,2)}).Equals(New With {Key .a = 1, .b="DIFFERENT Text", Key .c=New S(1,2)})) Console.WriteLine((New With {Key .a = 1, .b="text", Key .c=New S(1,2)}).Equals(New With {Key .a = 1, .b="text", Key .c=New S(2,1)})) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ True True False ]]>). VerifyIL("VB$AnonymousType_0(Of T0, T1, T2).Equals(VB$AnonymousType_0(Of T0, T1, T2))", <![CDATA[ { // Code size 111 (0x6f) .maxstack 2 .locals init (Object V_0, Object V_1) IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_006d IL_0004: ldarg.1 IL_0005: brfalse.s IL_006b IL_0007: ldarg.0 IL_0008: ldfld "VB$AnonymousType_0(Of T0, T1, T2).$a As T0" IL_000d: box "T0" IL_0012: stloc.0 IL_0013: ldarg.1 IL_0014: ldfld "VB$AnonymousType_0(Of T0, T1, T2).$a As T0" IL_0019: box "T0" IL_001e: stloc.1 IL_001f: ldloc.0 IL_0020: brfalse.s IL_0025 IL_0022: ldloc.1 IL_0023: brtrue.s IL_002b IL_0025: ldloc.0 IL_0026: ldloc.1 IL_0027: ceq IL_0029: br.s IL_0037 IL_002b: ldloc.0 IL_002c: ldloc.1 IL_002d: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0032: callvirt "Function Object.Equals(Object) As Boolean" IL_0037: brfalse.s IL_0069 IL_0039: ldarg.0 IL_003a: ldfld "VB$AnonymousType_0(Of T0, T1, T2).$c As T2" IL_003f: box "T2" IL_0044: stloc.0 IL_0045: ldarg.1 IL_0046: ldfld "VB$AnonymousType_0(Of T0, T1, T2).$c As T2" IL_004b: box "T2" IL_0050: stloc.1 IL_0051: ldloc.0 IL_0052: brfalse.s IL_0057 IL_0054: ldloc.1 IL_0055: brtrue.s IL_005c IL_0057: ldloc.0 IL_0058: ldloc.1 IL_0059: ceq IL_005b: ret IL_005c: ldloc.0 IL_005d: ldloc.1 IL_005e: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0063: callvirt "Function Object.Equals(Object) As Boolean" IL_0068: ret IL_0069: ldc.i4.0 IL_006a: ret IL_006b: ldc.i4.0 IL_006c: ret IL_006d: ldc.i4.1 IL_006e: ret } ]]>) End Sub <Fact()> Public Sub TestAnonymousType_Equals() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Structure S Public X As Integer Public Y As Integer Public Sub New(_x As Integer, _y As Integer) Me.X = _x Me.Y = _y End Sub Public Sub New(_x As Integer) Me.X = 0 Me.Y = 0 End Sub End Structure Sub Main(args As String()) Dim o1 As Object = New With {Key .a = 1, .b="text", Key .c=New S(1,2)} Dim o2 As Object = New With {Key .a = 1, .b="text", Key .c=New S(1,2)} Dim o3 As Object = New With {Key .a = 1, .b="DIFFERENT Text", Key .c=New S(1,2)} Dim o4 As Object = New With {Key .a = 1, .b="text", Key .c=New S(2,1)} Console.WriteLine(o1.Equals(o1)) Console.WriteLine(o1.Equals(o2)) Console.WriteLine(o1.Equals(o3)) Console.WriteLine(o1.Equals(o4)) Console.WriteLine(o2.Equals(o1)) Console.WriteLine(o2.Equals(o2)) Console.WriteLine(o2.Equals(o3)) Console.WriteLine(o2.Equals(o4)) Console.WriteLine(o3.Equals(o1)) Console.WriteLine(o3.Equals(o2)) Console.WriteLine(o3.Equals(o3)) Console.WriteLine(o3.Equals(o4)) Console.WriteLine(o4.Equals(o1)) Console.WriteLine(o4.Equals(o2)) Console.WriteLine(o4.Equals(o3)) Console.WriteLine(o4.Equals(o4)) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ True True True False True True True False True True True False False False False True ]]>). VerifyIL("VB$AnonymousType_0(Of T0, T1, T2).Equals(Object)", <![CDATA[ { // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: isinst "VB$AnonymousType_0(Of T0, T1, T2)" IL_0007: call "Function VB$AnonymousType_0(Of T0, T1, T2).Equals(VB$AnonymousType_0(Of T0, T1, T2)) As Boolean" IL_000c: ret } ]]>) End Sub <Fact()> Public Sub TestAnonymousType_GetHashCode() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) Dim obj As Object = New With {Key .a = 1, .b="text", Key .C = 1} End Sub End Module </file> </compilation>). VerifyIL("VB$AnonymousType_0(Of T0, T1, T2).GetHashCode()", New XCData(<![CDATA[ { // Code size 92 (0x5c) .maxstack 2 .locals init (T0 V_0, T2 V_1) IL_0000: ldc.i4 0x526a854f IL_0005: ldc.i4 0xa5555529 IL_000a: mul IL_000b: ldarg.0 IL_000c: ldfld "VB$AnonymousType_0(Of T0, T1, T2).$a As T0" IL_0011: box "T0" IL_0016: brfalse.s IL_002e IL_0018: ldarg.0 IL_0019: ldfld "VB$AnonymousType_0(Of T0, T1, T2).$a As T0" IL_001e: stloc.0 IL_001f: ldloca.s V_0 IL_0021: constrained. "T0" IL_0027: callvirt "Function Object.GetHashCode() As Integer" IL_002c: br.s IL_002f IL_002e: ldc.i4.0 IL_002f: add IL_0030: ldc.i4 0xa5555529 IL_0035: mul IL_0036: ldarg.0 IL_0037: ldfld "VB$AnonymousType_0(Of T0, T1, T2).$C As T2" IL_003c: box "T2" IL_0041: brfalse.s IL_0059 IL_0043: ldarg.0 IL_0044: ldfld "VB$AnonymousType_0(Of T0, T1, T2).$C As T2" IL_0049: stloc.1 IL_004a: ldloca.s V_1 IL_004c: constrained. "T2" IL_0052: callvirt "Function Object.GetHashCode() As Integer" IL_0057: br.s IL_005a IL_0059: ldc.i4.0 IL_005a: add IL_005b: ret } ]]>.Value)) End Sub <WorkItem(531571, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531571")> <Fact()> Public Sub Bug_531571() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Friend Module Program Sub Main() Console.WriteLine((New With {Key .prop1 = 1, Key .prop2 = 5.5}).GetHashCode()) End Sub End Module </file> </compilation>, expectedOutput:="-1644666626") End Sub <Fact()> Public Sub TestAnonymousType_GetHashCode02() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Sub Main() Dim at1 As Object = New With {.f1 = 123, Key .f2 = 456, Key .f3 = "XXX", .f4 = 123.456!} ' Changes in non-key fields Dim at2 As Object = New With {.f1 = "YYY", Key .f2 = 456, Key .f3 = "XXX", .f4 = Nothing } ' Changes in Key fields Dim at3 As Object = New With {.f1 = 123, Key .f2 = 455, Key .f3 = "XXX", .f4 = 123.456!} Dim hc1 = at1.GetHashCode() Console.WriteLine(hc1 = at2.GetHashCode ) Console.WriteLine(hc1 = at3.GetHashCode) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ True False ]]>) End Sub <Fact()> Public Sub TestAnonymousType_GetHashCode03() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Sub Main() Dim at1 As Object = New With {.LJ1 = 123, Key .LJ2 = 456, Key .LJ3 = "XXX", .LJ4 = 123.456!} ' Value changes in non-key fields, casing changes in all fields that require a recent unicode version Dim at2 As Object = New With {.Lj1 = "YYY", Key .Lj2 = 456, Key .Lj3 = "XXX", .Lj4 = Nothing } ' Value changes in Key fields Dim at3 As Object = New With {.LJ1 = 123, Key .LJ2 = 455, Key .LJ3 = "XXX", .LJ4 = 123.456!} Dim hc1 = at1.GetHashCode() Console.WriteLine(hc1 = at2.GetHashCode ) Console.WriteLine(hc1 = at3.GetHashCode) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ True False ]]>) End Sub <Fact()> Public Sub TestAnonymousType_SequenceOfInitializers() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Property Index As Integer Function F() As Integer Index = Index + 1 Console.WriteLine(Index) Return Index End Function Sub Main() Console.WriteLine(New With {F, Key .a = F, Key .b = .a, .c = F, .d = .b}) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 { F = 1, a = 2, b = 2, c = 3, d = 2 } ]]>) End Sub <Fact()> Public Sub TestAnonymousType_LocalAsNewWith() ' AnonymousType ToString Dim currCulture = System.Threading.Thread.CurrentThread.CurrentCulture System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture Try CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Sub Main() Dim a As New With { Key .a = 1, .b = .a * 0.1 } Console.WriteLine(a.ToString()) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[{ a = 1, b = 0.1 }]]>). VerifyIL("Program.Main()", <![CDATA[ { // Code size 31 (0x1f) .maxstack 3 .locals init (Integer V_0) IL_0000: ldc.i4.1 IL_0001: dup IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: conv.r8 IL_0005: ldc.r8 0.1 IL_000e: mul IL_000f: newobj "Sub VB$AnonymousType_0(Of Integer, Double)..ctor(Integer, Double)" IL_0014: callvirt "Function VB$AnonymousType_0(Of Integer, Double).ToString() As String" IL_0019: call "Sub System.Console.WriteLine(String)" IL_001e: ret } ]]>) Catch ex As Exception Assert.Null(ex) Finally System.Threading.Thread.CurrentThread.CurrentCulture = currCulture End Try End Sub <ConditionalFact(GetType(DesktopOnly))> Public Sub TestAnonymousTypeWithOptionInferOn() CompileAndVerify( <compilation> <file name="at.vb"><![CDATA[ Option Infer On Imports System Friend Module AnonTProp001mod Sub Main() Dim obj = New C Try Dim scen1 = New With {.With = "aclass", ._p_ = "C"c, Goo, Key New C().extMethod} Console.WriteLine("{0},{1},{2},{3}", scen1.With, scen1._p_, scen1.goo, scen1.Extmethod) Dim scen2 = New With {obj.Extmethod02, obj!_123, C.APROP} Console.WriteLine("{0},{1},{2}", scen2.ExtMethod02, scen2._123, scen2.aprop) Try Dim scen4 = New With {.prop1 = GooEx("testing")} Console.WriteLine("NO EX") Catch ex As Exception Console.WriteLine("Exp EX") End Try Catch Finally End Try End Sub Function Goo() As String Return "Abc" End Function Function GooEx(ByVal p1 As String) As String Throw New Exception("This exception is expected") End Function <System.Runtime.CompilerServices.Extension()> _ Friend Function ExtMethod(ByVal p1 As C) As String Return "Extended" End Function <System.Runtime.CompilerServices.Extension()> _ Function ExtMethod02(p1 As C) As Byte Return 127 End Function Class C Public ReadOnly Default Property Idx(p As String) As String Get Return p & p End Get End Property Friend Shared Property aprop() As String Get Return "wello horld" End Get Set(ByVal value As String) End Set End Property End Class End Module ]]></file> </compilation>, expectedOutput:=<![CDATA[ aclass,C,Abc,Extended 127,_123_123,wello horld Exp EX ]]>) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.IO Imports System.Threading.Tasks Imports System.Xml.Linq Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class AnonymousTypesCodeGenTests Inherits BasicTestBase <Fact()> Public Sub TestSimpleAnonymousType() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) Dim a As Integer = (New With {.a = 1, .b="text"}).a Dim b As String = (New With {.a = 1, .b="text"}).B Console.WriteLine(String.Format(".a={0}; .b={1}", a, b)) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ .a=1; .b=text ]]>). VerifyIL("VB$AnonymousType_0(Of T0, T1).get_a()", <![CDATA[ { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld "VB$AnonymousType_0(Of T0, T1).$a As T0" IL_0006: ret } ]]>). VerifyIL("VB$AnonymousType_0(Of T0, T1).set_a(T0)", <![CDATA[ { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld "VB$AnonymousType_0(Of T0, T1).$a As T0" IL_0007: ret } ]]>). VerifyIL("VB$AnonymousType_0(Of T0, T1).get_b()", <![CDATA[ { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld "VB$AnonymousType_0(Of T0, T1).$b As T1" IL_0006: ret } ]]>). VerifyIL("VB$AnonymousType_0(Of T0, T1).set_b(T1)", <![CDATA[ { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld "VB$AnonymousType_0(Of T0, T1).$b As T1" IL_0007: ret } ]]>). VerifyIL("VB$AnonymousType_0(Of T0, T1)..ctor(T0, T1)", <![CDATA[ { // Code size 21 (0x15) .maxstack 2 IL_0000: ldarg.0 IL_0001: call "Sub Object..ctor()" IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: stfld "VB$AnonymousType_0(Of T0, T1).$a As T0" IL_000d: ldarg.0 IL_000e: ldarg.2 IL_000f: stfld "VB$AnonymousType_0(Of T0, T1).$b As T1" IL_0014: ret } ]]>) End Sub <Fact> Public Sub AnonymousTypeSymbol_Simple_Threadsafety() Dim source = <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim at1 = New With {.a = 1, .b = 2} Dim at2 = New With {.a = 1, .b = 2, .c = 3} Dim at3 = New With {.a = 1, .b = 2, .c = 3, .d = 4} Dim at4 = New With {.a = 1, .b = 2, .c = 3, .d = 4, .e = 5} Dim at5 = New With {.a = 1, .b = 2, .c = 3, .d = 4, .e = 5, .f = 6} Dim at6 = New With {.a = 1, .b = 2, .c = 3, .d = 4, .e = 5, .f = 6, .g = 7} Dim at7 = New With {.a = 1, .b = 2, .c = 3, .d = 4, .e = 5, .f = 6, .g = 7, .h = 8} Dim at8 = New With {.a = 1, .b = 2, .c = 3, .d = 4, .e = 5, .f = 6, .g = 7, .h = 8, .j = 9} Dim at9 = New With {.a = 1, .b = 2, .c = 3, .d = 4, .e = 5, .f = 6, .g = 7, .h = 8, .j = 9, .k = 10} Dim at11 = New With {.aa = 1, .b = 2} Dim at12 = New With {.aa = 1, .b = 2, .c = 3} Dim at13 = New With {.aa = 1, .b = 2, .c = 3, .d = 4} Dim at14 = New With {.aa = 1, .b = 2, .c = 3, .d = 4, .e = 5} Dim at15 = New With {.aa = 1, .b = 2, .c = 3, .d = 4, .e = 5, .f = 6} Dim at16 = New With {.aa = 1, .b = 2, .c = 3, .d = 4, .e = 5, .f = 6, .g = 7} Dim at17 = New With {.aa = 1, .b = 2, .c = 3, .d = 4, .e = 5, .f = 6, .g = 7, .h = 8} Dim at18 = New With {.aa = 1, .b = 2, .c = 3, .d = 4, .e = 5, .f = 6, .g = 7, .h = 8, .j = 9} Dim at19 = New With {.aa = 1, .b = 2, .c = 3, .d = 4, .e = 5, .f = 6, .g = 7, .h = 8, .j = 9, .k = 10} Dim at21 = New With {.ba = 1, .b = 2} Dim at22 = New With {.ba = 1, .b = 2, .c = 3} Dim at23 = New With {.ba = 1, .b = 2, .c = 3, .d = 4} Dim at24 = New With {.ba = 1, .b = 2, .c = 3, .d = 4, .e = 5} Dim at25 = New With {.ba = 1, .b = 2, .c = 3, .d = 4, .e = 5, .f = 6} Dim at26 = New With {.ba = 1, .b = 2, .c = 3, .d = 4, .e = 5, .f = 6, .g = 7} Dim at27 = New With {.ba = 1, .b = 2, .c = 3, .d = 4, .e = 5, .f = 6, .g = 7, .h = 8} Dim at28 = New With {.ba = 1, .b = 2, .c = 3, .d = 4, .e = 5, .f = 6, .g = 7, .h = 8, .j = 9} Dim at29 = New With {.ba = 1, .b = 2, .c = 3, .d = 4, .e = 5, .f = 6, .g = 7, .h = 8, .j = 9, .k = 10} Dim at31 = New With {.ca = 1, .b = 2} Dim at32 = New With {.ca = 1, .b = 2, .c = 3} Dim at33 = New With {.ca = 1, .b = 2, .c = 3, .d = 4} Dim at34 = New With {.ca = 1, .b = 2, .c = 3, .d = 4, .e = 5} Dim at35 = New With {.ca = 1, .b = 2, .c = 3, .d = 4, .e = 5, .f = 6} Dim at36 = New With {.ca = 1, .b = 2, .c = 3, .d = 4, .e = 5, .f = 6, .g = 7} Dim at37 = New With {.ca = 1, .b = 2, .c = 3, .d = 4, .e = 5, .f = 6, .g = 7, .h = 8} Dim at38 = New With {.ca = 1, .b = 2, .c = 3, .d = 4, .e = 5, .f = 6, .g = 7, .h = 8, .j = 9} Dim at39 = New With {.ca = 1, .b = 2, .c = 3, .d = 4, .e = 5, .f = 6, .g = 7, .h = 8, .j = 9, .k = 10} Dim at41 = New With {.da = 1, .b = 2} Dim at42 = New With {.da = 1, .b = 2, .c = 3} Dim at43 = New With {.da = 1, .b = 2, .c = 3, .d = 4} Dim at44 = New With {.da = 1, .b = 2, .c = 3, .d = 4, .e = 5} Dim at45 = New With {.da = 1, .b = 2, .c = 3, .d = 4, .e = 5, .f = 6} Dim at46 = New With {.da = 1, .b = 2, .c = 3, .d = 4, .e = 5, .f = 6, .g = 7} Dim at47 = New With {.da = 1, .b = 2, .c = 3, .d = 4, .e = 5, .f = 6, .g = 7, .h = 8} Dim at48 = New With {.da = 1, .b = 2, .c = 3, .d = 4, .e = 5, .f = 6, .g = 7, .h = 8, .j = 9} Dim at49 = New With {.da = 1, .b = 2, .c = 3, .d = 4, .e = 5, .f = 6, .g = 7, .h = 8, .j = 9, .k = 10} End Sub End Module </file> </compilation> For i = 0 To 100 Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source) Dim tasks(10) As Task For jj = 0 To tasks.Length - 1 Dim j = jj tasks(j) = Task.Run(Sub() Dim stream = New MemoryStream() Dim result = compilation.Emit(stream, options:=New EmitOptions(metadataOnly:=j Mod 2 = 0)) result.Diagnostics.Verify() End Sub) Next ' this should Not fail. if you ever see a NRE Or some kind of crash here enter a bug. ' it may be reproducing just once in a while, in Release only... ' it Is still a bug. Task.WaitAll(tasks) Next End Sub <WorkItem(544243, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544243")> <Fact()> Public Sub TestAnonymousTypeInUnreachableCode_If1() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Test Sub Main(args() As String) If False Then Dim dummy As Object = New With {.a = 1} End If Console.WriteLine(If(GetType(Test).Assembly.GetType("VB$AnonymousType_0`1"), "Type Not Found")) End Sub End Module </file> </compilation>, expectedOutput:="VB$AnonymousType_0`1[T0]") End Sub <WorkItem(544243, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544243")> <Fact()> Public Sub TestAnonymousTypeInUnreachableCode_If2() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Test Sub Main(args() As String) If False Then Dim dummy = New With {.a = 1} End If Console.WriteLine(If(GetType(Test).Assembly.GetType("VB$AnonymousType_0`1"), "Type Not Found")) End Sub End Module </file> </compilation>, expectedOutput:="VB$AnonymousType_0`1[T0]") End Sub <WorkItem(544243, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544243")> <Fact()> Public Sub TestAnonymousTypeInUnreachableCode_If3() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Test Sub Main(args() As String) If False Then Dim dummy = New With {.a = New With {.b = 1}} End If Console.WriteLine(If(GetType(Test).Assembly.GetType("VB$AnonymousType_0`1"), "Type Not Found")) End Sub End Module </file> </compilation>, expectedOutput:="VB$AnonymousType_0`1[T0]") End Sub <WorkItem(544243, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544243")> <Fact()> Public Sub TestAnonymousTypeInUnreachableCode_Conditional1() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Test Sub Main(args() As String) Dim dummy As Object = If(False, New With {.a = 1}, Nothing) Console.WriteLine(If(GetType(Test).Assembly.GetType("VB$AnonymousType_0`1"), "Type Not Found")) End Sub End Module </file> </compilation>, expectedOutput:="VB$AnonymousType_0`1[T0]") End Sub <WorkItem(544243, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544243")> <Fact()> Public Sub TestAnonymousTypeInUnreachableCode_Conditional2() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Test Sub Main(args() As String) Dim dummy = If(False, New With {.a = 1}, Nothing) Console.WriteLine(If(GetType(Test).Assembly.GetType("VB$AnonymousType_0`1"), "Type Not Found")) End Sub End Module </file> </compilation>, expectedOutput:="VB$AnonymousType_0`1[T0]") End Sub <WorkItem(544243, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544243")> <Fact()> Public Sub TestAnonymousTypeInUnreachableCode_Conditional3() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Test Sub Main(args() As String) Dim dummy = If(False, New With {.a = New With {.b = 1}}, Nothing) Console.WriteLine(If(GetType(Test).Assembly.GetType("VB$AnonymousType_0`1"), "Type Not Found")) End Sub End Module </file> </compilation>, expectedOutput:="VB$AnonymousType_0`1[T0]") End Sub <WorkItem(544243, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544243")> <Fact()> Public Sub TestAnonymousTypeInUnreachableCode_Conditional4() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Test Sub Main(args() As String) Dim dummy = If("abc", New With {.a = New With {.b = 1}}) Console.WriteLine(If(GetType(Test).Assembly.GetType("VB$AnonymousType_0`1"), "Type Not Found")) End Sub End Module </file> </compilation>, expectedOutput:="VB$AnonymousType_0`1[T0]") End Sub <WorkItem(544243, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544243")> <Fact()> Public Sub TestAnonymousTypeInUnreachableCode_Conditional5() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Test Sub Main(args() As String) Dim dummy = If("abc", Sub() Dim a = New With {.a = New With {.b = 1}} End Sub) Console.WriteLine(If(GetType(Test).Assembly.GetType("VB$AnonymousType_0`1"), "Type Not Found")) End Sub End Module </file> </compilation>, expectedOutput:="VB$AnonymousType_0`1[T0]") End Sub <WorkItem(544243, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544243")> <Fact()> Public Sub TestAnonymousTypeInUnreachableCode_Conditional_CollInitializer1() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Test Sub Main(args() As String) Dim dummy As Object = If(False, { New With {.a = 1} }, Nothing) Console.WriteLine(If(GetType(Test).Assembly.GetType("VB$AnonymousType_0`1"), "Type Not Found")) End Sub End Module </file> </compilation>, expectedOutput:="VB$AnonymousType_0`1[T0]") End Sub <WorkItem(544243, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544243")> <Fact()> Public Sub TestAnonymousTypeInUnreachableCode_Conditional_CollInitializer2() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Test Sub Main(args() As String) Dim dummy = If(False, { New With {.a = 1} }, Nothing) Console.WriteLine(If(GetType(Test).Assembly.GetType("VB$AnonymousType_0`1"), "Type Not Found")) End Sub End Module </file> </compilation>, expectedOutput:="VB$AnonymousType_0`1[T0]") End Sub <Fact()> Public Sub TestAnonymousType_ToString() ' test AnonymousType_ToString() itself Dim currCulture = System.Threading.Thread.CurrentThread.CurrentCulture System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture Try CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) Console.WriteLine((New With {Key .a = 1, .b="text", Key .c=123.456}).ToString()) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ { a = 1, b = text, c = 123.456 } ]]>). VerifyIL("VB$AnonymousType_0(Of T0, T1, T2).ToString()", <![CDATA[ { // Code size 60 (0x3c) .maxstack 6 IL_0000: ldnull IL_0001: ldstr "{{ a = {0}, b = {1}, c = {2} }}" IL_0006: ldc.i4.3 IL_0007: newarr "Object" IL_000c: dup IL_000d: ldc.i4.0 IL_000e: ldarg.0 IL_000f: ldfld "VB$AnonymousType_0(Of T0, T1, T2).$a As T0" IL_0014: box "T0" IL_0019: stelem.ref IL_001a: dup IL_001b: ldc.i4.1 IL_001c: ldarg.0 IL_001d: ldfld "VB$AnonymousType_0(Of T0, T1, T2).$b As T1" IL_0022: box "T1" IL_0027: stelem.ref IL_0028: dup IL_0029: ldc.i4.2 IL_002a: ldarg.0 IL_002b: ldfld "VB$AnonymousType_0(Of T0, T1, T2).$c As T2" IL_0030: box "T2" IL_0035: stelem.ref IL_0036: call "Function String.Format(System.IFormatProvider, String, ParamArray Object()) As String" IL_003b: ret } ]]>) Catch ex As Exception Assert.Null(ex) Finally System.Threading.Thread.CurrentThread.CurrentCulture = currCulture End Try End Sub <Fact()> Public Sub TestAnonymousType_IEquatable_Equals() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Structure S Public X As Integer Public Y As Integer Public Sub New(_x As Integer, _y As Integer) Me.X = _x Me.Y = _y End Sub Public Sub New(_x As Integer) Me.X = 0 Me.Y = 0 End Sub End Structure Sub Main(args As String()) Console.WriteLine((New With {Key .a = 1, .b="text", Key .c=New S(1,2)}).Equals(New With {Key .a = 1, .b="text", Key .c=New S(1,2)})) Console.WriteLine((New With {Key .a = 1, .b="text", Key .c=New S(1,2)}).Equals(New With {Key .a = 1, .b="DIFFERENT Text", Key .c=New S(1,2)})) Console.WriteLine((New With {Key .a = 1, .b="text", Key .c=New S(1,2)}).Equals(New With {Key .a = 1, .b="text", Key .c=New S(2,1)})) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ True True False ]]>). VerifyIL("VB$AnonymousType_0(Of T0, T1, T2).Equals(VB$AnonymousType_0(Of T0, T1, T2))", <![CDATA[ { // Code size 111 (0x6f) .maxstack 2 .locals init (Object V_0, Object V_1) IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_006d IL_0004: ldarg.1 IL_0005: brfalse.s IL_006b IL_0007: ldarg.0 IL_0008: ldfld "VB$AnonymousType_0(Of T0, T1, T2).$a As T0" IL_000d: box "T0" IL_0012: stloc.0 IL_0013: ldarg.1 IL_0014: ldfld "VB$AnonymousType_0(Of T0, T1, T2).$a As T0" IL_0019: box "T0" IL_001e: stloc.1 IL_001f: ldloc.0 IL_0020: brfalse.s IL_0025 IL_0022: ldloc.1 IL_0023: brtrue.s IL_002b IL_0025: ldloc.0 IL_0026: ldloc.1 IL_0027: ceq IL_0029: br.s IL_0037 IL_002b: ldloc.0 IL_002c: ldloc.1 IL_002d: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0032: callvirt "Function Object.Equals(Object) As Boolean" IL_0037: brfalse.s IL_0069 IL_0039: ldarg.0 IL_003a: ldfld "VB$AnonymousType_0(Of T0, T1, T2).$c As T2" IL_003f: box "T2" IL_0044: stloc.0 IL_0045: ldarg.1 IL_0046: ldfld "VB$AnonymousType_0(Of T0, T1, T2).$c As T2" IL_004b: box "T2" IL_0050: stloc.1 IL_0051: ldloc.0 IL_0052: brfalse.s IL_0057 IL_0054: ldloc.1 IL_0055: brtrue.s IL_005c IL_0057: ldloc.0 IL_0058: ldloc.1 IL_0059: ceq IL_005b: ret IL_005c: ldloc.0 IL_005d: ldloc.1 IL_005e: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0063: callvirt "Function Object.Equals(Object) As Boolean" IL_0068: ret IL_0069: ldc.i4.0 IL_006a: ret IL_006b: ldc.i4.0 IL_006c: ret IL_006d: ldc.i4.1 IL_006e: ret } ]]>) End Sub <Fact()> Public Sub TestAnonymousType_Equals() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Structure S Public X As Integer Public Y As Integer Public Sub New(_x As Integer, _y As Integer) Me.X = _x Me.Y = _y End Sub Public Sub New(_x As Integer) Me.X = 0 Me.Y = 0 End Sub End Structure Sub Main(args As String()) Dim o1 As Object = New With {Key .a = 1, .b="text", Key .c=New S(1,2)} Dim o2 As Object = New With {Key .a = 1, .b="text", Key .c=New S(1,2)} Dim o3 As Object = New With {Key .a = 1, .b="DIFFERENT Text", Key .c=New S(1,2)} Dim o4 As Object = New With {Key .a = 1, .b="text", Key .c=New S(2,1)} Console.WriteLine(o1.Equals(o1)) Console.WriteLine(o1.Equals(o2)) Console.WriteLine(o1.Equals(o3)) Console.WriteLine(o1.Equals(o4)) Console.WriteLine(o2.Equals(o1)) Console.WriteLine(o2.Equals(o2)) Console.WriteLine(o2.Equals(o3)) Console.WriteLine(o2.Equals(o4)) Console.WriteLine(o3.Equals(o1)) Console.WriteLine(o3.Equals(o2)) Console.WriteLine(o3.Equals(o3)) Console.WriteLine(o3.Equals(o4)) Console.WriteLine(o4.Equals(o1)) Console.WriteLine(o4.Equals(o2)) Console.WriteLine(o4.Equals(o3)) Console.WriteLine(o4.Equals(o4)) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ True True True False True True True False True True True False False False False True ]]>). VerifyIL("VB$AnonymousType_0(Of T0, T1, T2).Equals(Object)", <![CDATA[ { // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: isinst "VB$AnonymousType_0(Of T0, T1, T2)" IL_0007: call "Function VB$AnonymousType_0(Of T0, T1, T2).Equals(VB$AnonymousType_0(Of T0, T1, T2)) As Boolean" IL_000c: ret } ]]>) End Sub <Fact()> Public Sub TestAnonymousType_GetHashCode() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) Dim obj As Object = New With {Key .a = 1, .b="text", Key .C = 1} End Sub End Module </file> </compilation>). VerifyIL("VB$AnonymousType_0(Of T0, T1, T2).GetHashCode()", New XCData(<![CDATA[ { // Code size 92 (0x5c) .maxstack 2 .locals init (T0 V_0, T2 V_1) IL_0000: ldc.i4 0x526a854f IL_0005: ldc.i4 0xa5555529 IL_000a: mul IL_000b: ldarg.0 IL_000c: ldfld "VB$AnonymousType_0(Of T0, T1, T2).$a As T0" IL_0011: box "T0" IL_0016: brfalse.s IL_002e IL_0018: ldarg.0 IL_0019: ldfld "VB$AnonymousType_0(Of T0, T1, T2).$a As T0" IL_001e: stloc.0 IL_001f: ldloca.s V_0 IL_0021: constrained. "T0" IL_0027: callvirt "Function Object.GetHashCode() As Integer" IL_002c: br.s IL_002f IL_002e: ldc.i4.0 IL_002f: add IL_0030: ldc.i4 0xa5555529 IL_0035: mul IL_0036: ldarg.0 IL_0037: ldfld "VB$AnonymousType_0(Of T0, T1, T2).$C As T2" IL_003c: box "T2" IL_0041: brfalse.s IL_0059 IL_0043: ldarg.0 IL_0044: ldfld "VB$AnonymousType_0(Of T0, T1, T2).$C As T2" IL_0049: stloc.1 IL_004a: ldloca.s V_1 IL_004c: constrained. "T2" IL_0052: callvirt "Function Object.GetHashCode() As Integer" IL_0057: br.s IL_005a IL_0059: ldc.i4.0 IL_005a: add IL_005b: ret } ]]>.Value)) End Sub <WorkItem(531571, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531571")> <Fact()> Public Sub Bug_531571() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Friend Module Program Sub Main() Console.WriteLine((New With {Key .prop1 = 1, Key .prop2 = 5.5}).GetHashCode()) End Sub End Module </file> </compilation>, expectedOutput:="-1644666626") End Sub <Fact()> Public Sub TestAnonymousType_GetHashCode02() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Sub Main() Dim at1 As Object = New With {.f1 = 123, Key .f2 = 456, Key .f3 = "XXX", .f4 = 123.456!} ' Changes in non-key fields Dim at2 As Object = New With {.f1 = "YYY", Key .f2 = 456, Key .f3 = "XXX", .f4 = Nothing } ' Changes in Key fields Dim at3 As Object = New With {.f1 = 123, Key .f2 = 455, Key .f3 = "XXX", .f4 = 123.456!} Dim hc1 = at1.GetHashCode() Console.WriteLine(hc1 = at2.GetHashCode ) Console.WriteLine(hc1 = at3.GetHashCode) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ True False ]]>) End Sub <Fact()> Public Sub TestAnonymousType_GetHashCode03() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Sub Main() Dim at1 As Object = New With {.LJ1 = 123, Key .LJ2 = 456, Key .LJ3 = "XXX", .LJ4 = 123.456!} ' Value changes in non-key fields, casing changes in all fields that require a recent unicode version Dim at2 As Object = New With {.Lj1 = "YYY", Key .Lj2 = 456, Key .Lj3 = "XXX", .Lj4 = Nothing } ' Value changes in Key fields Dim at3 As Object = New With {.LJ1 = 123, Key .LJ2 = 455, Key .LJ3 = "XXX", .LJ4 = 123.456!} Dim hc1 = at1.GetHashCode() Console.WriteLine(hc1 = at2.GetHashCode ) Console.WriteLine(hc1 = at3.GetHashCode) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ True False ]]>) End Sub <Fact()> Public Sub TestAnonymousType_SequenceOfInitializers() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Property Index As Integer Function F() As Integer Index = Index + 1 Console.WriteLine(Index) Return Index End Function Sub Main() Console.WriteLine(New With {F, Key .a = F, Key .b = .a, .c = F, .d = .b}) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 { F = 1, a = 2, b = 2, c = 3, d = 2 } ]]>) End Sub <Fact()> Public Sub TestAnonymousType_LocalAsNewWith() ' AnonymousType ToString Dim currCulture = System.Threading.Thread.CurrentThread.CurrentCulture System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture Try CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Program Sub Main() Dim a As New With { Key .a = 1, .b = .a * 0.1 } Console.WriteLine(a.ToString()) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[{ a = 1, b = 0.1 }]]>). VerifyIL("Program.Main()", <![CDATA[ { // Code size 31 (0x1f) .maxstack 3 .locals init (Integer V_0) IL_0000: ldc.i4.1 IL_0001: dup IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: conv.r8 IL_0005: ldc.r8 0.1 IL_000e: mul IL_000f: newobj "Sub VB$AnonymousType_0(Of Integer, Double)..ctor(Integer, Double)" IL_0014: callvirt "Function VB$AnonymousType_0(Of Integer, Double).ToString() As String" IL_0019: call "Sub System.Console.WriteLine(String)" IL_001e: ret } ]]>) Catch ex As Exception Assert.Null(ex) Finally System.Threading.Thread.CurrentThread.CurrentCulture = currCulture End Try End Sub <ConditionalFact(GetType(DesktopOnly))> Public Sub TestAnonymousTypeWithOptionInferOn() CompileAndVerify( <compilation> <file name="at.vb"><![CDATA[ Option Infer On Imports System Friend Module AnonTProp001mod Sub Main() Dim obj = New C Try Dim scen1 = New With {.With = "aclass", ._p_ = "C"c, Goo, Key New C().extMethod} Console.WriteLine("{0},{1},{2},{3}", scen1.With, scen1._p_, scen1.goo, scen1.Extmethod) Dim scen2 = New With {obj.Extmethod02, obj!_123, C.APROP} Console.WriteLine("{0},{1},{2}", scen2.ExtMethod02, scen2._123, scen2.aprop) Try Dim scen4 = New With {.prop1 = GooEx("testing")} Console.WriteLine("NO EX") Catch ex As Exception Console.WriteLine("Exp EX") End Try Catch Finally End Try End Sub Function Goo() As String Return "Abc" End Function Function GooEx(ByVal p1 As String) As String Throw New Exception("This exception is expected") End Function <System.Runtime.CompilerServices.Extension()> _ Friend Function ExtMethod(ByVal p1 As C) As String Return "Extended" End Function <System.Runtime.CompilerServices.Extension()> _ Function ExtMethod02(p1 As C) As Byte Return 127 End Function Class C Public ReadOnly Default Property Idx(p As String) As String Get Return p & p End Get End Property Friend Shared Property aprop() As String Get Return "wello horld" End Get Set(ByVal value As String) End Set End Property End Class End Module ]]></file> </compilation>, expectedOutput:=<![CDATA[ aclass,C,Abc,Extended 127,_123_123,wello horld Exp EX ]]>) End Sub End Class End Namespace
-1
dotnet/roslyn
55,409
Use FixedSize API
tmat
2021-08-04T19:30:40Z
2021-08-04T21:53:46Z
e0112742bff208dd0546de45e36f7b52058a45a3
c90bf0ec986010051662c8e1fbc872c2fd86bc4e
Use FixedSize API.
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Utilities/TextReaderWithLength.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.IO; namespace Microsoft.CodeAnalysis.Shared.Utilities { internal abstract class TextReaderWithLength : TextReader { public TextReaderWithLength(int length) => Length = length; public int Length { 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.IO; namespace Microsoft.CodeAnalysis.Shared.Utilities { internal abstract class TextReaderWithLength : TextReader { public TextReaderWithLength(int length) => Length = length; public int Length { get; } } }
-1
dotnet/roslyn
55,409
Use FixedSize API
tmat
2021-08-04T19:30:40Z
2021-08-04T21:53:46Z
e0112742bff208dd0546de45e36f7b52058a45a3
c90bf0ec986010051662c8e1fbc872c2fd86bc4e
Use FixedSize API.
./src/EditorFeatures/Core.Wpf/ConflictTagDefinition.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel.Composition; using System.Diagnostics.CodeAnalysis; using System.Windows.Media; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Shared.Tagging.Tags { [Export(typeof(EditorFormatDefinition))] [Name(ConflictTag.TagId)] [UserVisible(true)] [ExcludeFromCodeCoverage] internal class ConflictTagDefinition : MarkerFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ConflictTagDefinition() { this.Border = new Pen(Brushes.Red, thickness: 1.5); this.DisplayName = EditorFeaturesResources.Conflict; this.ZOrder = 10; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel.Composition; using System.Diagnostics.CodeAnalysis; using System.Windows.Media; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Shared.Tagging.Tags { [Export(typeof(EditorFormatDefinition))] [Name(ConflictTag.TagId)] [UserVisible(true)] [ExcludeFromCodeCoverage] internal class ConflictTagDefinition : MarkerFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ConflictTagDefinition() { this.Border = new Pen(Brushes.Red, thickness: 1.5); this.DisplayName = EditorFeaturesResources.Conflict; this.ZOrder = 10; } } }
-1
dotnet/roslyn
55,409
Use FixedSize API
tmat
2021-08-04T19:30:40Z
2021-08-04T21:53:46Z
e0112742bff208dd0546de45e36f7b52058a45a3
c90bf0ec986010051662c8e1fbc872c2fd86bc4e
Use FixedSize API.
./src/Features/Core/Portable/Completion/Providers/Scripting/GlobalAssemblyCacheCompletionHelper.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Completion.Providers { internal sealed class GlobalAssemblyCacheCompletionHelper { private static readonly Lazy<List<string>> s_lazyAssemblySimpleNames = new(() => GlobalAssemblyCache.Instance.GetAssemblySimpleNames().ToList()); private readonly CompletionItemRules _itemRules; public GlobalAssemblyCacheCompletionHelper(CompletionItemRules itemRules) { Debug.Assert(itemRules != null); _itemRules = itemRules; } public Task<ImmutableArray<CompletionItem>> GetItemsAsync(string directoryPath, CancellationToken cancellationToken) => Task.Run(() => GetItems(directoryPath, cancellationToken)); // internal for testing internal ImmutableArray<CompletionItem> GetItems(string directoryPath, CancellationToken cancellationToken) { using var resultDisposer = ArrayBuilder<CompletionItem>.GetInstance(out var result); var comma = directoryPath.IndexOf(','); if (comma >= 0) { var partialName = directoryPath.Substring(0, comma); foreach (var identity in GetAssemblyIdentities(partialName)) { result.Add(CommonCompletionItem.Create( identity.GetDisplayName(), displayTextSuffix: "", glyph: Glyph.Assembly, rules: _itemRules)); } } else { foreach (var displayName in s_lazyAssemblySimpleNames.Value) { cancellationToken.ThrowIfCancellationRequested(); result.Add(CommonCompletionItem.Create( displayName, displayTextSuffix: "", glyph: Glyph.Assembly, rules: _itemRules)); } } return result.ToImmutable(); } private static IEnumerable<AssemblyIdentity> GetAssemblyIdentities(string partialName) { return IOUtilities.PerformIO(() => GlobalAssemblyCache.Instance.GetAssemblyIdentities(partialName), SpecializedCollections.EmptyEnumerable<AssemblyIdentity>()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Completion.Providers { internal sealed class GlobalAssemblyCacheCompletionHelper { private static readonly Lazy<List<string>> s_lazyAssemblySimpleNames = new(() => GlobalAssemblyCache.Instance.GetAssemblySimpleNames().ToList()); private readonly CompletionItemRules _itemRules; public GlobalAssemblyCacheCompletionHelper(CompletionItemRules itemRules) { Debug.Assert(itemRules != null); _itemRules = itemRules; } public Task<ImmutableArray<CompletionItem>> GetItemsAsync(string directoryPath, CancellationToken cancellationToken) => Task.Run(() => GetItems(directoryPath, cancellationToken)); // internal for testing internal ImmutableArray<CompletionItem> GetItems(string directoryPath, CancellationToken cancellationToken) { using var resultDisposer = ArrayBuilder<CompletionItem>.GetInstance(out var result); var comma = directoryPath.IndexOf(','); if (comma >= 0) { var partialName = directoryPath.Substring(0, comma); foreach (var identity in GetAssemblyIdentities(partialName)) { result.Add(CommonCompletionItem.Create( identity.GetDisplayName(), displayTextSuffix: "", glyph: Glyph.Assembly, rules: _itemRules)); } } else { foreach (var displayName in s_lazyAssemblySimpleNames.Value) { cancellationToken.ThrowIfCancellationRequested(); result.Add(CommonCompletionItem.Create( displayName, displayTextSuffix: "", glyph: Glyph.Assembly, rules: _itemRules)); } } return result.ToImmutable(); } private static IEnumerable<AssemblyIdentity> GetAssemblyIdentities(string partialName) { return IOUtilities.PerformIO(() => GlobalAssemblyCache.Instance.GetAssemblyIdentities(partialName), SpecializedCollections.EmptyEnumerable<AssemblyIdentity>()); } } }
-1
dotnet/roslyn
55,409
Use FixedSize API
tmat
2021-08-04T19:30:40Z
2021-08-04T21:53:46Z
e0112742bff208dd0546de45e36f7b52058a45a3
c90bf0ec986010051662c8e1fbc872c2fd86bc4e
Use FixedSize API.
./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_MultipleLocalDeclarations.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { public override BoundNode? VisitMultipleLocalDeclarations(BoundMultipleLocalDeclarations node) { return VisitMultipleLocalDeclarationsBase(node); } public override BoundNode? VisitUsingLocalDeclarations(BoundUsingLocalDeclarations node) { return VisitMultipleLocalDeclarationsBase(node); } private BoundNode? VisitMultipleLocalDeclarationsBase(BoundMultipleLocalDeclarationsBase node) { ArrayBuilder<BoundStatement>? inits = null; foreach (var decl in node.LocalDeclarations) { var init = VisitLocalDeclaration(decl); if (init != null) { if (inits == null) { inits = ArrayBuilder<BoundStatement>.GetInstance(); } inits.Add((BoundStatement)init); } } if (inits != null) { return BoundStatementList.Synthesized(node.Syntax, node.HasErrors, inits.ToImmutableAndFree()); } else { // no initializers return null; // TODO: but what if hasErrors? Have we lost that? } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { public override BoundNode? VisitMultipleLocalDeclarations(BoundMultipleLocalDeclarations node) { return VisitMultipleLocalDeclarationsBase(node); } public override BoundNode? VisitUsingLocalDeclarations(BoundUsingLocalDeclarations node) { return VisitMultipleLocalDeclarationsBase(node); } private BoundNode? VisitMultipleLocalDeclarationsBase(BoundMultipleLocalDeclarationsBase node) { ArrayBuilder<BoundStatement>? inits = null; foreach (var decl in node.LocalDeclarations) { var init = VisitLocalDeclaration(decl); if (init != null) { if (inits == null) { inits = ArrayBuilder<BoundStatement>.GetInstance(); } inits.Add((BoundStatement)init); } } if (inits != null) { return BoundStatementList.Synthesized(node.Syntax, node.HasErrors, inits.ToImmutableAndFree()); } else { // no initializers return null; // TODO: but what if hasErrors? Have we lost that? } } } }
-1
dotnet/roslyn
55,409
Use FixedSize API
tmat
2021-08-04T19:30:40Z
2021-08-04T21:53:46Z
e0112742bff208dd0546de45e36f7b52058a45a3
c90bf0ec986010051662c8e1fbc872c2fd86bc4e
Use FixedSize API.
./src/EditorFeatures/Core.Wpf/Suggestions/SuggestedActions/SuggestedAction.CaretPositionRestorer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Suggestions { internal partial class SuggestedAction { internal class CaretPositionRestorer : IDisposable { // Bug 5535: By default the standard editor caret is set to have positive affinity. This // means that if text is added right at the caret then the caret moves to the right and // is placed after the added text. However, we don't want that. Instead, we want the // caret to stay where it started at. So we store the caret position here and // restore it afterwards. private readonly EventHandler<CaretPositionChangedEventArgs> _caretPositionChangedHandler; private readonly IList<Tuple<ITextView, IMappingPoint>> _caretPositions; private readonly ITextBuffer _subjectBuffer; private readonly ITextBufferAssociatedViewService _associatedViewService; private bool _caretChanged; public CaretPositionRestorer(ITextBuffer subjectBuffer, ITextBufferAssociatedViewService associatedViewService) { Contract.ThrowIfNull(associatedViewService); _subjectBuffer = subjectBuffer; _caretPositionChangedHandler = (s, e) => _caretChanged = true; _associatedViewService = associatedViewService; _caretPositions = GetCaretPositions(); } private IList<Tuple<ITextView, IMappingPoint>> GetCaretPositions() { // Currently, only do this if there's a single view var views = _associatedViewService.GetAssociatedTextViews(_subjectBuffer); var result = new List<Tuple<ITextView, IMappingPoint>>(); foreach (var view in views) { view.Caret.PositionChanged += _caretPositionChangedHandler; var point = view.GetCaretPoint(_subjectBuffer); if (point != null) { result.Add(Tuple.Create(view, view.BufferGraph.CreateMappingPoint(point.Value, PointTrackingMode.Negative))); } } return result; } private void RestoreCaretPositions() { if (_caretChanged) { return; } foreach (var tuple in _caretPositions) { var position = tuple.Item1.GetCaretPoint(_subjectBuffer); if (position != null) { var view = tuple.Item1; if (!view.IsClosed) { view.TryMoveCaretToAndEnsureVisible(position.Value); } } } } public void Dispose() { RestoreCaretPositions(); foreach (var tuple in _caretPositions) { tuple.Item1.Caret.PositionChanged -= _caretPositionChangedHandler; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Suggestions { internal partial class SuggestedAction { internal class CaretPositionRestorer : IDisposable { // Bug 5535: By default the standard editor caret is set to have positive affinity. This // means that if text is added right at the caret then the caret moves to the right and // is placed after the added text. However, we don't want that. Instead, we want the // caret to stay where it started at. So we store the caret position here and // restore it afterwards. private readonly EventHandler<CaretPositionChangedEventArgs> _caretPositionChangedHandler; private readonly IList<Tuple<ITextView, IMappingPoint>> _caretPositions; private readonly ITextBuffer _subjectBuffer; private readonly ITextBufferAssociatedViewService _associatedViewService; private bool _caretChanged; public CaretPositionRestorer(ITextBuffer subjectBuffer, ITextBufferAssociatedViewService associatedViewService) { Contract.ThrowIfNull(associatedViewService); _subjectBuffer = subjectBuffer; _caretPositionChangedHandler = (s, e) => _caretChanged = true; _associatedViewService = associatedViewService; _caretPositions = GetCaretPositions(); } private IList<Tuple<ITextView, IMappingPoint>> GetCaretPositions() { // Currently, only do this if there's a single view var views = _associatedViewService.GetAssociatedTextViews(_subjectBuffer); var result = new List<Tuple<ITextView, IMappingPoint>>(); foreach (var view in views) { view.Caret.PositionChanged += _caretPositionChangedHandler; var point = view.GetCaretPoint(_subjectBuffer); if (point != null) { result.Add(Tuple.Create(view, view.BufferGraph.CreateMappingPoint(point.Value, PointTrackingMode.Negative))); } } return result; } private void RestoreCaretPositions() { if (_caretChanged) { return; } foreach (var tuple in _caretPositions) { var position = tuple.Item1.GetCaretPoint(_subjectBuffer); if (position != null) { var view = tuple.Item1; if (!view.IsClosed) { view.TryMoveCaretToAndEnsureVisible(position.Value); } } } } public void Dispose() { RestoreCaretPositions(); foreach (var tuple in _caretPositions) { tuple.Item1.Caret.PositionChanged -= _caretPositionChangedHandler; } } } } }
-1
dotnet/roslyn
55,409
Use FixedSize API
tmat
2021-08-04T19:30:40Z
2021-08-04T21:53:46Z
e0112742bff208dd0546de45e36f7b52058a45a3
c90bf0ec986010051662c8e1fbc872c2fd86bc4e
Use FixedSize API.
./src/Compilers/Core/Portable/MetadataReference/AssemblyIdentityParts.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis { [Flags] public enum AssemblyIdentityParts { Name = 1, Version = VersionMajor | VersionMinor | VersionBuild | VersionRevision, // version parts are assumed to be in order: VersionMajor = 1 << 1, VersionMinor = 1 << 2, VersionBuild = 1 << 3, VersionRevision = 1 << 4, Culture = 1 << 5, PublicKey = 1 << 6, PublicKeyToken = 1 << 7, PublicKeyOrToken = PublicKey | PublicKeyToken, Retargetability = 1 << 8, ContentType = 1 << 9, Unknown = 1 << 10 } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis { [Flags] public enum AssemblyIdentityParts { Name = 1, Version = VersionMajor | VersionMinor | VersionBuild | VersionRevision, // version parts are assumed to be in order: VersionMajor = 1 << 1, VersionMinor = 1 << 2, VersionBuild = 1 << 3, VersionRevision = 1 << 4, Culture = 1 << 5, PublicKey = 1 << 6, PublicKeyToken = 1 << 7, PublicKeyOrToken = PublicKey | PublicKeyToken, Retargetability = 1 << 8, ContentType = 1 << 9, Unknown = 1 << 10 } }
-1
dotnet/roslyn
55,409
Use FixedSize API
tmat
2021-08-04T19:30:40Z
2021-08-04T21:53:46Z
e0112742bff208dd0546de45e36f7b52058a45a3
c90bf0ec986010051662c8e1fbc872c2fd86bc4e
Use FixedSize API.
./src/VisualStudio/IntegrationTest/TestUtilities/InProcess/GenerateTypeDialog_InProc.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Linq; using System.Threading; using Microsoft.VisualStudio.IntegrationTest.Utilities.Input; using Microsoft.VisualStudio.LanguageServices.Implementation.GenerateType; using Roslyn.Utilities; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess { internal class GenerateTypeDialog_InProc : AbstractCodeRefactorDialog_InProc<GenerateTypeDialog, GenerateTypeDialog.TestAccessor> { private GenerateTypeDialog_InProc() { } public static GenerateTypeDialog_InProc Create() => new GenerateTypeDialog_InProc(); public override void VerifyOpen() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { var cancellationToken = cancellationTokenSource.Token; while (true) { cancellationToken.ThrowIfCancellationRequested(); var window = JoinableTaskFactory.Run(() => TryGetDialogAsync(cancellationToken)); if (window is null) { // Thread.Yield is insufficient; something in the light bulb must be relying on a UI thread // message at lower priority than the Background priority used in testing. WaitForApplicationIdle(Helper.HangMitigatingTimeout); continue; } WaitForApplicationIdle(Helper.HangMitigatingTimeout); return; } } } public bool CloseWindow() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { if (JoinableTaskFactory.Run(() => TryGetDialogAsync(cancellationTokenSource.Token)) is null) { return false; } } ClickCancel(); return true; } public void ClickOK() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(() => ClickAsync(testAccessor => testAccessor.OKButton, cancellationTokenSource.Token)); } } public void ClickCancel() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(() => ClickAsync(testAccessor => testAccessor.CancelButton, cancellationTokenSource.Token)); } } public void SetAccessibility(string accessibility) { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); var dialog = await GetDialogAsync(cancellationTokenSource.Token); Contract.ThrowIfFalse(await dialog.GetTestAccessor().AccessListComboBox.SimulateSelectItemAsync(JoinableTaskFactory, accessibility)); }); } } public void SetKind(string kind) { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); var dialog = await GetDialogAsync(cancellationTokenSource.Token); Contract.ThrowIfFalse(await dialog.GetTestAccessor().KindListComboBox.SimulateSelectItemAsync(JoinableTaskFactory, kind)); }); } } public void SetTargetProject(string projectName) { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); var dialog = await GetDialogAsync(cancellationTokenSource.Token); Contract.ThrowIfFalse(await dialog.GetTestAccessor().ProjectListComboBox.SimulateSelectItemAsync(JoinableTaskFactory, projectName)); }); } } public void SetTargetFileToNewName(string newFileName) { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); var dialog = await GetDialogAsync(cancellationTokenSource.Token); Contract.ThrowIfFalse(await dialog.GetTestAccessor().CreateNewFileRadioButton.SimulateClickAsync(JoinableTaskFactory)); Contract.ThrowIfFalse(await dialog.GetTestAccessor().CreateNewFileComboBox.SimulateSelectItemAsync(JoinableTaskFactory, newFileName, mustExist: false)); }); } } public void SetTargetFileToExisting(string existingFileName) { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); var dialog = await GetDialogAsync(cancellationTokenSource.Token); Contract.ThrowIfFalse(await dialog.GetTestAccessor().AddToExistingFileRadioButton.SimulateClickAsync(JoinableTaskFactory)); Contract.ThrowIfFalse(await dialog.GetTestAccessor().AddToExistingFileComboBox.SimulateSelectItemAsync(JoinableTaskFactory, existingFileName, mustExist: false)); }); } } public string[] GetNewFileComboBoxItems() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { return JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); var dialog = await GetDialogAsync(cancellationTokenSource.Token); return dialog.GetTestAccessor().CreateNewFileComboBox.Items.Cast<string>().ToArray(); }); } } protected override GenerateTypeDialog.TestAccessor GetAccessor(GenerateTypeDialog dialog) => dialog.GetTestAccessor(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Linq; using System.Threading; using Microsoft.VisualStudio.IntegrationTest.Utilities.Input; using Microsoft.VisualStudio.LanguageServices.Implementation.GenerateType; using Roslyn.Utilities; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess { internal class GenerateTypeDialog_InProc : AbstractCodeRefactorDialog_InProc<GenerateTypeDialog, GenerateTypeDialog.TestAccessor> { private GenerateTypeDialog_InProc() { } public static GenerateTypeDialog_InProc Create() => new GenerateTypeDialog_InProc(); public override void VerifyOpen() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { var cancellationToken = cancellationTokenSource.Token; while (true) { cancellationToken.ThrowIfCancellationRequested(); var window = JoinableTaskFactory.Run(() => TryGetDialogAsync(cancellationToken)); if (window is null) { // Thread.Yield is insufficient; something in the light bulb must be relying on a UI thread // message at lower priority than the Background priority used in testing. WaitForApplicationIdle(Helper.HangMitigatingTimeout); continue; } WaitForApplicationIdle(Helper.HangMitigatingTimeout); return; } } } public bool CloseWindow() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { if (JoinableTaskFactory.Run(() => TryGetDialogAsync(cancellationTokenSource.Token)) is null) { return false; } } ClickCancel(); return true; } public void ClickOK() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(() => ClickAsync(testAccessor => testAccessor.OKButton, cancellationTokenSource.Token)); } } public void ClickCancel() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(() => ClickAsync(testAccessor => testAccessor.CancelButton, cancellationTokenSource.Token)); } } public void SetAccessibility(string accessibility) { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); var dialog = await GetDialogAsync(cancellationTokenSource.Token); Contract.ThrowIfFalse(await dialog.GetTestAccessor().AccessListComboBox.SimulateSelectItemAsync(JoinableTaskFactory, accessibility)); }); } } public void SetKind(string kind) { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); var dialog = await GetDialogAsync(cancellationTokenSource.Token); Contract.ThrowIfFalse(await dialog.GetTestAccessor().KindListComboBox.SimulateSelectItemAsync(JoinableTaskFactory, kind)); }); } } public void SetTargetProject(string projectName) { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); var dialog = await GetDialogAsync(cancellationTokenSource.Token); Contract.ThrowIfFalse(await dialog.GetTestAccessor().ProjectListComboBox.SimulateSelectItemAsync(JoinableTaskFactory, projectName)); }); } } public void SetTargetFileToNewName(string newFileName) { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); var dialog = await GetDialogAsync(cancellationTokenSource.Token); Contract.ThrowIfFalse(await dialog.GetTestAccessor().CreateNewFileRadioButton.SimulateClickAsync(JoinableTaskFactory)); Contract.ThrowIfFalse(await dialog.GetTestAccessor().CreateNewFileComboBox.SimulateSelectItemAsync(JoinableTaskFactory, newFileName, mustExist: false)); }); } } public void SetTargetFileToExisting(string existingFileName) { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); var dialog = await GetDialogAsync(cancellationTokenSource.Token); Contract.ThrowIfFalse(await dialog.GetTestAccessor().AddToExistingFileRadioButton.SimulateClickAsync(JoinableTaskFactory)); Contract.ThrowIfFalse(await dialog.GetTestAccessor().AddToExistingFileComboBox.SimulateSelectItemAsync(JoinableTaskFactory, existingFileName, mustExist: false)); }); } } public string[] GetNewFileComboBoxItems() { using (var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout)) { return JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); var dialog = await GetDialogAsync(cancellationTokenSource.Token); return dialog.GetTestAccessor().CreateNewFileComboBox.Items.Cast<string>().ToArray(); }); } } protected override GenerateTypeDialog.TestAccessor GetAccessor(GenerateTypeDialog dialog) => dialog.GetTestAccessor(); } }
-1
dotnet/roslyn
55,409
Use FixedSize API
tmat
2021-08-04T19:30:40Z
2021-08-04T21:53:46Z
e0112742bff208dd0546de45e36f7b52058a45a3
c90bf0ec986010051662c8e1fbc872c2fd86bc4e
Use FixedSize API.
./src/EditorFeatures/CSharpTest/EditAndContinue/TopLevelEditingTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.EditAndContinue.UnitTests; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { [UseExportProvider] public class TopLevelEditingTests : EditingTestBase { #region Usings [Fact] public void Using_Global_Insert() { var src1 = @" using System.Collections.Generic; "; var src2 = @" global using D = System.Diagnostics; global using System.Collections; using System.Collections.Generic; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [global using D = System.Diagnostics;]@2", "Insert [global using System.Collections;]@40"); edits.VerifyRudeDiagnostics(); } [Fact] public void Using_Delete1() { var src1 = @" using System.Diagnostics; "; var src2 = @""; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [using System.Diagnostics;]@2"); Assert.IsType<UsingDirectiveSyntax>(edits.Edits.First().OldNode); Assert.Null(edits.Edits.First().NewNode); } [Fact] public void Using_Delete2() { var src1 = @" using D = System.Diagnostics; using System.Collections; using System.Collections.Generic; "; var src2 = @" using System.Collections.Generic; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [using D = System.Diagnostics;]@2", "Delete [using System.Collections;]@33"); edits.VerifyRudeDiagnostics(); } [Fact] public void Using_Insert() { var src1 = @" using System.Collections.Generic; "; var src2 = @" using D = System.Diagnostics; using System.Collections; using System.Collections.Generic; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [using D = System.Diagnostics;]@2", "Insert [using System.Collections;]@33"); edits.VerifyRudeDiagnostics(); } [Fact] public void Using_Update1() { var src1 = @" using System.Diagnostics; using System.Collections; using System.Collections.Generic; "; var src2 = @" using System.Diagnostics; using X = System.Collections; using System.Collections.Generic; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [using System.Collections;]@29 -> [using X = System.Collections;]@29"); edits.VerifyRudeDiagnostics(); } [Fact] public void Using_Update2() { var src1 = @" using System.Diagnostics; using X1 = System.Collections; using System.Collections.Generic; "; var src2 = @" using System.Diagnostics; using X2 = System.Collections; using System.Collections.Generic; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [using X1 = System.Collections;]@29 -> [using X2 = System.Collections;]@29"); edits.VerifyRudeDiagnostics(); } [Fact] public void Using_Update3() { var src1 = @" using System.Diagnostics; using System.Collections; using System.Collections.Generic; "; var src2 = @" using System; using System.Collections; using System.Collections.Generic; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [using System.Diagnostics;]@2 -> [using System;]@2"); edits.VerifyRudeDiagnostics(); } [Fact] public void Using_Reorder1() { var src1 = @" using System.Diagnostics; using System.Collections; using System.Collections.Generic; "; var src2 = @" using System.Collections; using System.Collections.Generic; using System.Diagnostics; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [using System.Diagnostics;]@2 -> @64"); } [Fact] public void Using_InsertDelete1() { var src1 = @" namespace N { using System.Collections; } namespace M { } "; var src2 = @" namespace N { } namespace M { using System.Collections; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [using System.Collections;]@43", "Delete [using System.Collections;]@22"); } [Fact] public void Using_InsertDelete2() { var src1 = @" namespace N { using System.Collections; } "; var src2 = @" using System.Collections; namespace N { } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [using System.Collections;]@2", "Delete [using System.Collections;]@22"); } [Fact] public void Using_Delete_ChangesCodeMeaning() { // This test specifically validates the scenario we _don't_ support, namely when inserting or deleting // a using directive, if existing code changes in meaning as a result, we don't issue edits for that code. // If this ever regresses then please buy a lottery ticket because the feature has magically fixed itself. var src1 = @" using System.IO; using DirectoryInfo = N.C; namespace N { public class C { public C(string a) { } public FileAttributes Attributes { get; set; } } public class D { public void M() { var d = new DirectoryInfo(""aa""); var x = directoryInfo.Attributes; } } }"; var src2 = @" using System.IO; namespace N { public class C { public C(string a) { } public FileAttributes Attributes { get; set; } } public class D { public void M() { var d = new DirectoryInfo(""aa""); var x = directoryInfo.Attributes; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [using DirectoryInfo = N.C;]@20"); edits.VerifySemantics(); } [Fact] public void Using_Insert_ForNewCode() { // As distinct from the above, this test validates a real world scenario of inserting a using directive // and changing code that utilizes the new directive to some effect. var src1 = @" namespace N { class Program { static void Main(string[] args) { } } }"; var src2 = @" using System; namespace N { class Program { static void Main(string[] args) { Console.WriteLine(""Hello World!""); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("N.Program.Main"))); } [Fact] public void Using_Delete_ForOldCode() { var src1 = @" using System; namespace N { class Program { static void Main(string[] args) { Console.WriteLine(""Hello World!""); } } }"; var src2 = @" namespace N { class Program { static void Main(string[] args) { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("N.Program.Main"))); } [Fact] public void Using_Insert_CreatesAmbiguousCode() { // This test validates that we still issue edits for changed valid code, even when unchanged // code has ambiguities after adding a using. var src1 = @" using System.Threading; namespace N { class C { void M() { // Timer exists in System.Threading and System.Timers var t = new Timer(s => System.Console.WriteLine(s)); } } }"; var src2 = @" using System.Threading; using System.Timers; namespace N { class C { void M() { // Timer exists in System.Threading and System.Timers var t = new Timer(s => System.Console.WriteLine(s)); } void M2() { // TimersDescriptionAttribute only exists in System.Timers System.Console.WriteLine(new TimersDescriptionAttribute("""")); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("N.C.M2"))); } #endregion #region Extern Alias [Fact] public void ExternAliasUpdate() { var src1 = "extern alias X;"; var src2 = "extern alias Y;"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [extern alias X;]@0 -> [extern alias Y;]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Update, "extern alias Y;", CSharpFeaturesResources.extern_alias)); } [Fact] public void ExternAliasInsert() { var src1 = ""; var src2 = "extern alias Y;"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [extern alias Y;]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "extern alias Y;", CSharpFeaturesResources.extern_alias)); } [Fact] public void ExternAliasDelete() { var src1 = "extern alias Y;"; var src2 = ""; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [extern alias Y;]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, null, CSharpFeaturesResources.extern_alias)); } #endregion #region Assembly/Module Attributes [Fact] public void Insert_TopLevelAttribute() { var src1 = ""; var src2 = "[assembly: System.Obsolete(\"2\")]"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [[assembly: System.Obsolete(\"2\")]]@0", "Insert [System.Obsolete(\"2\")]@11"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "[assembly: System.Obsolete(\"2\")]", FeaturesResources.attribute)); } [Fact] public void Delete_TopLevelAttribute() { var src1 = "[assembly: System.Obsolete(\"2\")]"; var src2 = ""; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [[assembly: System.Obsolete(\"2\")]]@0", "Delete [System.Obsolete(\"2\")]@11"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, null, FeaturesResources.attribute)); } [Fact] public void Update_TopLevelAttribute() { var src1 = "[assembly: System.Obsolete(\"1\")]"; var src2 = "[assembly: System.Obsolete(\"2\")]"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[assembly: System.Obsolete(\"1\")]]@0 -> [[assembly: System.Obsolete(\"2\")]]@0", "Update [System.Obsolete(\"1\")]@11 -> [System.Obsolete(\"2\")]@11"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Update, "System.Obsolete(\"2\")", FeaturesResources.attribute)); } [Fact] public void Reorder_TopLevelAttribute() { var src1 = "[assembly: System.Obsolete(\"1\")][assembly: System.Obsolete(\"2\")]"; var src2 = "[assembly: System.Obsolete(\"2\")][assembly: System.Obsolete(\"1\")]"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [[assembly: System.Obsolete(\"2\")]]@32 -> @0"); edits.VerifyRudeDiagnostics(); } #endregion #region Types [Theory] [InlineData("class", "struct")] [InlineData("class", "record")] // TODO: Allow this conversion: https://github.com/dotnet/roslyn/issues/51874 [InlineData("class", "record struct")] [InlineData("class", "interface")] [InlineData("struct", "record struct")] // TODO: Allow this conversion: https://github.com/dotnet/roslyn/issues/51874 public void Type_Kind_Update(string oldKeyword, string newKeyword) { var src1 = oldKeyword + " C { }"; var src2 = newKeyword + " C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [" + oldKeyword + " C { }]@0 -> [" + newKeyword + " C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeKindUpdate, newKeyword + " C")); } [Theory] [InlineData("class", "struct")] [InlineData("class", "record")] [InlineData("class", "record struct")] [InlineData("class", "interface")] [InlineData("struct", "record struct")] public void Type_Kind_Update_Reloadable(string oldKeyword, string newKeyword) { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]" + oldKeyword + " C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]" + newKeyword + " C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[CreateNewOnMetadataUpdate]" + oldKeyword + " C { }]@145 -> [[CreateNewOnMetadataUpdate]" + newKeyword + " C { }]@145"); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Type_Modifiers_Static_Remove() { var src1 = "public static class C { }"; var src2 = "public class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public static class C { }]@0 -> [public class C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public class C", FeaturesResources.class_)); } [Theory] [InlineData("public")] [InlineData("protected")] [InlineData("private")] [InlineData("private protected")] [InlineData("internal protected")] public void Type_Modifiers_Accessibility_Change(string accessibility) { var src1 = accessibility + " class C { }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [" + accessibility + " class C { }]@0 -> [class C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "class C", FeaturesResources.class_)); } [Theory] [InlineData("public", "public")] [InlineData("internal", "internal")] [InlineData("", "internal")] [InlineData("internal", "")] [InlineData("protected", "protected")] [InlineData("private", "private")] [InlineData("private protected", "private protected")] [InlineData("internal protected", "internal protected")] public void Type_Modifiers_Accessibility_Partial(string accessibilityA, string accessibilityB) { var srcA1 = accessibilityA + " partial class C { }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = accessibilityB + " partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(), }); } [Fact] public void Type_Modifiers_Internal_Remove() { var src1 = "internal interface C { }"; var src2 = "interface C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Fact] public void Type_Modifiers_Internal_Add() { var src1 = "struct C { }"; var src2 = "internal struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Fact] public void Type_Modifiers_Accessibility_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]public class C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]internal class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[CreateNewOnMetadataUpdate]public class C { }]@145 -> [[CreateNewOnMetadataUpdate]internal class C { }]@145"); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Theory] [InlineData("class")] [InlineData("struct")] [InlineData("interface")] [InlineData("record")] [InlineData("record struct")] public void Type_Modifiers_NestedPrivateInInterface_Remove(string keyword) { var src1 = "interface C { private " + keyword + " S { } }"; var src2 = "interface C { " + keyword + " S { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, keyword + " S", GetResource(keyword))); } [Theory] [InlineData("class")] [InlineData("struct")] [InlineData("interface")] [InlineData("record")] [InlineData("record struct")] public void Type_Modifiers_NestedPrivateInClass_Add(string keyword) { var src1 = "class C { " + keyword + " S { } }"; var src2 = "class C { private " + keyword + " S { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Theory] [InlineData("class")] [InlineData("struct")] [InlineData("interface")] [InlineData("record")] [InlineData("record struct")] public void Type_Modifiers_NestedPublicInInterface_Add(string keyword) { var src1 = "interface C { " + keyword + " S { } }"; var src2 = "interface C { public " + keyword + " S { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Fact, WorkItem(48628, "https://github.com/dotnet/roslyn/issues/48628")] public void Type_Modifiers_Unsafe_Add() { var src1 = "public class C { }"; var src2 = "public unsafe class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public class C { }]@0 -> [public unsafe class C { }]@0"); edits.VerifyRudeDiagnostics(); } [Fact, WorkItem(48628, "https://github.com/dotnet/roslyn/issues/48628")] public void Type_Modifiers_Unsafe_Remove() { var src1 = @" using System; unsafe delegate void D(); class C { unsafe class N { } public unsafe event Action<int> A { add { } remove { } } unsafe int F() => 0; unsafe int X; unsafe int Y { get; } unsafe C() {} unsafe ~C() {} } "; var src2 = @" using System; delegate void D(); class C { class N { } public event Action<int> A { add { } remove { } } int F() => 0; int X; int Y { get; } C() {} ~C() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [unsafe delegate void D();]@17 -> [delegate void D();]@17", "Update [unsafe class N { }]@60 -> [class N { }]@53", "Update [public unsafe event Action<int> A { add { } remove { } }]@84 -> [public event Action<int> A { add { } remove { } }]@70", "Update [unsafe int F() => 0;]@146 -> [int F() => 0;]@125", "Update [unsafe int X;]@172 -> [int X;]@144", "Update [unsafe int Y { get; }]@191 -> [int Y { get; }]@156", "Update [unsafe C() {}]@218 -> [C() {}]@176", "Update [unsafe ~C() {}]@237 -> [~C() {}]@188"); edits.VerifyRudeDiagnostics(); } [Fact, WorkItem(48628, "https://github.com/dotnet/roslyn/issues/48628")] public void Type_Modifiers_Unsafe_DeleteInsert() { var srcA1 = "partial class C { unsafe void F() { } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { void F() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F")) }), }); } [Fact] public void Type_Modifiers_Ref_Add() { var src1 = "public struct C { }"; var src2 = "public ref struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public struct C { }]@0 -> [public ref struct C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public ref struct C", CSharpFeaturesResources.struct_)); } [Fact] public void Type_Modifiers_Ref_Remove() { var src1 = "public ref struct C { }"; var src2 = "public struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public ref struct C { }]@0 -> [public struct C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public struct C", CSharpFeaturesResources.struct_)); } [Fact] public void Type_Modifiers_ReadOnly_Add() { var src1 = "public struct C { }"; var src2 = "public readonly struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public struct C { }]@0 -> [public readonly struct C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public readonly struct C", CSharpFeaturesResources.struct_)); } [Fact] public void Type_Modifiers_ReadOnly_Remove() { var src1 = "public readonly struct C { }"; var src2 = "public struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public readonly struct C { }]@0 -> [public struct C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public struct C", CSharpFeaturesResources.struct_)); } [Fact] public void Type_Attribute_Update_NotSupportedByRuntime1() { var attribute = "public class A1Attribute : System.Attribute { }\n\n" + "public class A2Attribute : System.Attribute { }\n\n"; var src1 = attribute + "[A1]class C { }"; var src2 = attribute + "[A2]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A1]class C { }]@98 -> [[A2]class C { }]@98"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Fact] public void Type_Attribute_Update_NotSupportedByRuntime2() { var src1 = "[System.Obsolete(\"1\")]class C { }"; var src2 = "[System.Obsolete(\"2\")]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete(\"1\")]class C { }]@0 -> [[System.Obsolete(\"2\")]class C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Fact] public void Type_Attribute_Delete_NotSupportedByRuntime1() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + "[A, B]class C { }"; var src2 = attribute + "[A]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A, B]class C { }]@96 -> [[A]class C { }]@96"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Fact] public void Type_Attribute_Delete_NotSupportedByRuntime2() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + "[B, A]class C { }"; var src2 = attribute + "[A]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[B, A]class C { }]@96 -> [[A]class C { }]@96"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Fact] public void Type_Attribute_Change_Reloadable() { var attributeSrc = @" public class A1 : System.Attribute { } public class A2 : System.Attribute { } public class A3 : System.Attribute { } "; var src1 = ReloadableAttributeSrc + attributeSrc + "[CreateNewOnMetadataUpdate, A1, A2]class C { }"; var src2 = ReloadableAttributeSrc + attributeSrc + "[CreateNewOnMetadataUpdate, A2, A3]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[CreateNewOnMetadataUpdate, A1, A2]class C { }]@267 -> [[CreateNewOnMetadataUpdate, A2, A3]class C { }]@267"); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Type_Attribute_ReloadableRemove() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var src2 = ReloadableAttributeSrc + "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Type_Attribute_ReloadableAdd() { var src1 = ReloadableAttributeSrc + "class C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Type_Attribute_ReloadableBase() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class B { } class C : B { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class B { } class C : B { void F() {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Type_Attribute_Add() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + "[A]class C { }"; var src2 = attribute + "[A, B]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]class C { }]@96 -> [[A, B]class C { }]@96"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Type_Attribute_Add_NotSupportedByRuntime1() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + "[A]class C { }"; var src2 = attribute + "[A, B]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]class C { }]@96 -> [[A, B]class C { }]@96"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Fact] public void Type_Attribute_Add_NotSupportedByRuntime2() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "class C { }"; var src2 = attribute + "[A]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [class C { }]@48 -> [[A]class C { }]@48"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Fact] public void Type_Attribute_Reorder1() { var src1 = "[A(1), B(2), C(3)]class C { }"; var src2 = "[C(3), A(1), B(2)]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A(1), B(2), C(3)]class C { }]@0 -> [[C(3), A(1), B(2)]class C { }]@0"); edits.VerifyRudeDiagnostics(); } [Fact] public void Type_Attribute_Reorder2() { var src1 = "[A, B, C]class C { }"; var src2 = "[B, C, A]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A, B, C]class C { }]@0 -> [[B, C, A]class C { }]@0"); edits.VerifyRudeDiagnostics(); } [Fact] public void Type_Attribute_ReorderAndUpdate_NotSupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + "[System.Obsolete(\"1\"), A, B]class C { }"; var src2 = attribute + "[A, B, System.Obsolete(\"2\")]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete(\"1\"), A, B]class C { }]@96 -> [[A, B, System.Obsolete(\"2\")]class C { }]@96"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Theory] [InlineData("class")] [InlineData("struct")] [InlineData("interface")] [InlineData("record")] [InlineData("record struct")] public void Type_Rename(string keyword) { var src1 = keyword + " C { }"; var src2 = keyword + " D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [" + keyword + " C { }]@0 -> [" + keyword + " D { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, keyword + " D", GetResource(keyword))); } [Fact] public void Type_Rename_AddAndDeleteMember() { var src1 = "class C { int x = 1; }"; var src2 = "class D { void F() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [class C { int x = 1; }]@0 -> [class D { void F() { } }]@0", "Insert [void F() { }]@10", "Insert [()]@16", "Delete [int x = 1;]@10", "Delete [int x = 1]@10", "Delete [x = 1]@14"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "class D", FeaturesResources.class_)); } [Fact] [WorkItem(54886, "https://github.com/dotnet/roslyn/issues/54886")] public void Type_Rename_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[CreateNewOnMetadataUpdate]class C { }]@145 -> [[CreateNewOnMetadataUpdate]class D { }]@145"); // TODO: expected: Replace edit of D edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Renamed, "class D", FeaturesResources.class_)); } [Fact] [WorkItem(54886, "https://github.com/dotnet/roslyn/issues/54886")] public void Type_Rename_Reloadable_AddAndDeleteMember() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { int x = 1; }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class D { void F() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[CreateNewOnMetadataUpdate]class C { int x = 1; }]@145 -> [[CreateNewOnMetadataUpdate]class D { void F() { } }]@145", "Insert [void F() { }]@182", "Insert [()]@188", "Delete [int x = 1;]@182", "Delete [int x = 1]@182", "Delete [x = 1]@186"); // TODO: expected: Replace edit of D edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Renamed, "class D", FeaturesResources.class_)); } [Fact] public void Interface_NoModifiers_Insert() { var src1 = ""; var src2 = "interface C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Interface_NoModifiers_IntoNamespace_Insert() { var src1 = "namespace N { } "; var src2 = "namespace N { interface C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Interface_NoModifiers_IntoType_Insert() { var src1 = "interface N { }"; var src2 = "interface N { interface C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Class_NoModifiers_Insert() { var src1 = ""; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Class_NoModifiers_IntoNamespace_Insert() { var src1 = "namespace N { }"; var src2 = "namespace N { class C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Class_NoModifiers_IntoType_Insert() { var src1 = "struct N { }"; var src2 = "struct N { class C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Struct_NoModifiers_Insert() { var src1 = ""; var src2 = "struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Struct_NoModifiers_IntoNamespace_Insert() { var src1 = "namespace N { }"; var src2 = "namespace N { struct C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Struct_NoModifiers_IntoType_Insert() { var src1 = "struct N { }"; var src2 = "struct N { struct C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Type_BaseType_Add_Unchanged() { var src1 = "class C { }"; var src2 = "class C : object { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [class C { }]@0 -> [class C : object { }]@0"); edits.VerifySemantics(); } [Fact] public void Type_BaseType_Add_Changed() { var src1 = "class C { }"; var src2 = "class C : D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [class C { }]@0 -> [class C : D { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class C", FeaturesResources.class_)); } [Theory] [InlineData("string", "string?")] [InlineData("string[]", "string[]?")] [InlineData("object", "dynamic")] [InlineData("dynamic?", "dynamic")] [InlineData("(int a, int b)", "(int a, int c)")] public void Type_BaseType_Update_RuntimeTypeUnchanged(string oldType, string newType) { var src1 = "class C : System.Collections.Generic.List<" + oldType + "> {}"; var src2 = "class C : System.Collections.Generic.List<" + newType + "> {}"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C"))); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void Type_BaseType_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C : System.Collections.Generic.List<" + oldType + "> {}"; var src2 = "class C : System.Collections.Generic.List<" + newType + "> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class C", FeaturesResources.class_)); } [Fact] public void Type_BaseType_Update_CompileTimeTypeUnchanged() { var src1 = "using A = System.Int32; using B = System.Int32; class C : System.Collections.Generic.List<A> {}"; var src2 = "using A = System.Int32; using B = System.Int32; class C : System.Collections.Generic.List<B> {}"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Fact] public void Type_BaseInterface_Add() { var src1 = "class C { }"; var src2 = "class C : IDisposable { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [class C { }]@0 -> [class C : IDisposable { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class C", FeaturesResources.class_)); } [Fact] public void Type_BaseInterface_Delete_Inherited() { var src1 = @" interface B {} interface A : B {} class C : A, B {} "; var src2 = @" interface B {} interface A : B {} class C : A {} "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Fact] public void Type_BaseInterface_Reorder() { var src1 = "class C : IGoo, IBar { }"; var src2 = "class C : IBar, IGoo { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [class C : IGoo, IBar { }]@0 -> [class C : IBar, IGoo { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class C", FeaturesResources.class_)); } [Theory] [InlineData("string", "string?")] [InlineData("object", "dynamic")] [InlineData("(int a, int b)", "(int a, int c)")] public void Type_BaseInterface_Update_RuntimeTypeUnchanged(string oldType, string newType) { var src1 = "class C : System.Collections.Generic.IEnumerable<" + oldType + "> {}"; var src2 = "class C : System.Collections.Generic.IEnumerable<" + newType + "> {}"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C"))); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void Type_BaseInterface_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C : System.Collections.Generic.IEnumerable<" + oldType + "> {}"; var src2 = "class C : System.Collections.Generic.IEnumerable<" + newType + "> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class C", FeaturesResources.class_)); } [Fact] public void Type_Base_Partial() { var srcA1 = "partial class C : B, I { }"; var srcB1 = "partial class C : J { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C : B, I, J { }"; var srcC = @" class B {} interface I {} interface J {}"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC, srcC) }, new[] { DocumentResults(), DocumentResults(), DocumentResults() }); } [Fact] public void Type_Base_Partial_InsertDeleteAndUpdate() { var srcA1 = "partial class C { }"; var srcB1 = ""; var srcC1 = "partial class C { }"; var srcA2 = ""; var srcB2 = "partial class C : D { }"; var srcC2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "partial class C", FeaturesResources.class_) }), DocumentResults(), }); } [Fact] public void Type_Base_InsertDelete() { var srcA1 = ""; var srcB1 = "class C : B, I { }"; var srcA2 = "class C : B, I { }"; var srcB2 = ""; var srcC = @" class B {} interface I {} interface J {}"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC, srcC) }, new[] { DocumentResults(), DocumentResults(), DocumentResults() }); } [Fact] public void Type_Reloadable_NotSupportedByRuntime() { var src1 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] public class C { void F() { System.Console.WriteLine(1); } }"; var src2 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] public class C { void F() { System.Console.WriteLine(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.ChangingReloadableTypeNotSupportedByRuntime, "void F()", "CreateNewOnMetadataUpdateAttribute")); } [Fact] public void Type_Insert_AbstractVirtualOverride() { var src1 = ""; var src2 = @" public abstract class C<T> { public abstract void F(); public virtual void G() {} public override string ToString() => null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Type_Insert_NotSupportedByRuntime() { var src1 = @" public class C { void F() { } }"; var src2 = @" public class C { void F() { } } public class D { void M() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "public class D", FeaturesResources.class_)); } [Fact] public void Type_Insert_Reloadable() { var src1 = ReloadableAttributeSrc + ""; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { void F() {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C"))); } [Fact] public void InterfaceInsert() { var src1 = ""; var src2 = @" public interface I { void F(); static void G() {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void RefStructInsert() { var src1 = ""; var src2 = "ref struct X { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [ref struct X { }]@0"); edits.VerifyRudeDiagnostics(); } [Fact] public void Struct_ReadOnly_Insert() { var src1 = ""; var src2 = "readonly struct X { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [readonly struct X { }]@0"); edits.VerifyRudeDiagnostics(); } [Fact] public void Struct_RefModifier_Add() { var src1 = "struct X { }"; var src2 = "ref struct X { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [struct X { }]@0 -> [ref struct X { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "ref struct X", CSharpFeaturesResources.struct_)); } [Fact] public void Struct_ReadonlyModifier_Add() { var src1 = "struct X { }"; var src2 = "readonly struct X { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [struct X { }]@0 -> [readonly struct X { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "readonly struct X", SyntaxFacts.GetText(SyntaxKind.StructKeyword))); } [Theory] [InlineData("ref")] [InlineData("readonly")] public void Struct_Modifiers_Partial_InsertDelete(string modifier) { var srcA1 = modifier + " partial struct S { }"; var srcB1 = "partial struct S { }"; var srcA2 = "partial struct S { }"; var srcB2 = modifier + " partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults() }); } [Fact] public void Class_ImplementingInterface_Add() { var src1 = @" using System; public interface ISample { string Get(); } public interface IConflict { string Get(); } public class BaseClass : ISample { public virtual string Get() => string.Empty; } "; var src2 = @" using System; public interface ISample { string Get(); } public interface IConflict { string Get(); } public class BaseClass : ISample { public virtual string Get() => string.Empty; } public class SubClass : BaseClass, IConflict { public override string Get() => string.Empty; string IConflict.Get() => String.Empty; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Insert [public class SubClass : BaseClass, IConflict { public override string Get() => string.Empty; string IConflict.Get() => String.Empty; }]@219", "Insert [public override string Get() => string.Empty;]@272", "Insert [string IConflict.Get() => String.Empty;]@325", "Insert [()]@298", "Insert [()]@345"); // Here we add a class implementing an interface and a method inside it with explicit interface specifier. // We want to be sure that adding the method will not tirgger a rude edit as it happens if adding a single method with explicit interface specifier. edits.VerifyRudeDiagnostics(); } [WorkItem(37128, "https://github.com/dotnet/roslyn/issues/37128")] [Fact] public void Interface_InsertMembers() { var src1 = @" using System; interface I { } "; var src2 = @" using System; interface I { static int StaticField = 10; static void StaticMethod() { } void VirtualMethod1() { } virtual void VirtualMethod2() { } abstract void AbstractMethod(); sealed void NonVirtualMethod() { } public static int operator +(I a, I b) => 1; static int StaticProperty1 { get => 1; set { } } static int StaticProperty2 => 1; virtual int VirtualProperty1 { get => 1; set { } } virtual int VirtualProperty2 { get => 1; } int VirtualProperty3 { get => 1; set { } } int VirtualProperty4 { get => 1; } abstract int AbstractProperty1 { get; set; } abstract int AbstractProperty2 { get; } sealed int NonVirtualProperty => 1; int this[byte virtualIndexer] => 1; int this[sbyte virtualIndexer] { get => 1; } virtual int this[ushort virtualIndexer] { get => 1; set {} } virtual int this[short virtualIndexer] { get => 1; set {} } abstract int this[uint abstractIndexer] { get; set; } abstract int this[int abstractIndexer] { get; } sealed int this[ulong nonVirtualIndexer] { get => 1; set {} } sealed int this[long nonVirtualIndexer] { get => 1; set {} } static event Action StaticEvent; static event Action StaticEvent2 { add { } remove { } } event Action VirtualEvent { add { } remove { } } abstract event Action AbstractEvent; sealed event Action NonVirtualEvent { add { } remove { } } abstract class C { } interface J { } enum E { } delegate void D(); } "; var edits = GetTopEdits(src1, src2); // TODO: InsertIntoInterface errors are reported due to https://github.com/dotnet/roslyn/issues/37128. edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoInterface, "static void StaticMethod()", FeaturesResources.method), Diagnostic(RudeEditKind.InsertVirtual, "void VirtualMethod1()", FeaturesResources.method), Diagnostic(RudeEditKind.InsertVirtual, "virtual void VirtualMethod2()", FeaturesResources.method), Diagnostic(RudeEditKind.InsertVirtual, "abstract void AbstractMethod()", FeaturesResources.method), Diagnostic(RudeEditKind.InsertIntoInterface, "sealed void NonVirtualMethod()", FeaturesResources.method), Diagnostic(RudeEditKind.InsertOperator, "public static int operator +(I a, I b)", FeaturesResources.operator_), Diagnostic(RudeEditKind.InsertIntoInterface, "static int StaticProperty1", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertIntoInterface, "static int StaticProperty2", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertIntoInterface, "static int StaticProperty2", CSharpFeaturesResources.property_getter), Diagnostic(RudeEditKind.InsertVirtual, "virtual int VirtualProperty1", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertVirtual, "virtual int VirtualProperty2", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertVirtual, "int VirtualProperty3", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertVirtual, "int VirtualProperty4", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertVirtual, "abstract int AbstractProperty1", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertVirtual, "abstract int AbstractProperty2", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertIntoInterface, "sealed int NonVirtualProperty", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertIntoInterface, "sealed int NonVirtualProperty", CSharpFeaturesResources.property_getter), Diagnostic(RudeEditKind.InsertVirtual, "int this[byte virtualIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertVirtual, "int this[byte virtualIndexer]", CSharpFeaturesResources.indexer_getter), Diagnostic(RudeEditKind.InsertVirtual, "int this[sbyte virtualIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertVirtual, "virtual int this[ushort virtualIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertVirtual, "virtual int this[short virtualIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertVirtual, "abstract int this[uint abstractIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertVirtual, "abstract int this[int abstractIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertIntoInterface, "sealed int this[ulong nonVirtualIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertIntoInterface, "sealed int this[long nonVirtualIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertIntoInterface, "static event Action StaticEvent2", FeaturesResources.event_), Diagnostic(RudeEditKind.InsertVirtual, "event Action VirtualEvent", FeaturesResources.event_), Diagnostic(RudeEditKind.InsertIntoInterface, "sealed event Action NonVirtualEvent", FeaturesResources.event_), Diagnostic(RudeEditKind.InsertIntoInterface, "StaticField = 10", FeaturesResources.field), Diagnostic(RudeEditKind.InsertIntoInterface, "StaticEvent", CSharpFeaturesResources.event_field), Diagnostic(RudeEditKind.InsertVirtual, "AbstractEvent", CSharpFeaturesResources.event_field)); } [Fact] public void Interface_InsertDelete() { var srcA1 = @" interface I { static void M() { } } "; var srcB1 = @" "; var srcA2 = @" "; var srcB2 = @" interface I { static void M() { } } "; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("M")) }), }); } [Fact] public void Type_Generic_InsertMembers() { var src1 = @" using System; class C<T> { } "; var src2 = @" using System; class C<T> { void M() {} int P1 { get; set; } int P2 { get => 1; set {} } int this[int i] { get => 1; set {} } event Action E { add {} remove {} } event Action EF; int F1, F2; enum E {} interface I {} class D {} } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoGenericType, "void M()", FeaturesResources.method), Diagnostic(RudeEditKind.InsertIntoGenericType, "int P1", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertIntoGenericType, "int P2", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertIntoGenericType, "int this[int i]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertIntoGenericType, "event Action E", FeaturesResources.event_), Diagnostic(RudeEditKind.InsertIntoGenericType, "EF", CSharpFeaturesResources.event_field), Diagnostic(RudeEditKind.InsertIntoGenericType, "F1", FeaturesResources.field), Diagnostic(RudeEditKind.InsertIntoGenericType, "F2", FeaturesResources.field)); } [Fact] public void Type_Generic_InsertMembers_Reloadable() { var src1 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] class C<T> { } "; var src2 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] class C<T> { void M() {} int P1 { get; set; } int P2 { get => 1; set {} } int this[int i] { get => 1; set {} } event System.Action E { add {} remove {} } event System.Action EF; int F1, F2; enum E {} interface I {} class D {} } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Type_Generic_DeleteInsert() { var srcA1 = @" class C<T> { void F() {} } struct S<T> { void F() {} } interface I<T> { void F() {} } "; var srcB1 = ""; var srcA2 = srcB1; var srcB2 = srcA1; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "class C<T>"), Diagnostic(RudeEditKind.GenericTypeUpdate, "struct S<T>"), Diagnostic(RudeEditKind.GenericTypeUpdate, "interface I<T>"), Diagnostic(RudeEditKind.GenericTypeUpdate, "void F()"), Diagnostic(RudeEditKind.GenericTypeUpdate, "void F()"), Diagnostic(RudeEditKind.GenericTypeUpdate, "void F()"), Diagnostic(RudeEditKind.GenericTypeUpdate, "T"), Diagnostic(RudeEditKind.GenericTypeUpdate, "T"), Diagnostic(RudeEditKind.GenericTypeUpdate, "T"), }) }); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/54881")] [WorkItem(54881, "https://github.com/dotnet/roslyn/issues/54881")] public void Type_TypeParameter_Insert_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]public class C<T> { void F() { } }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]internal class C<T, S> { int x = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Type_Delete() { var src1 = @" class C { void F() {} } struct S { void F() {} } interface I { void F() {} } "; var src2 = ""; GetTopEdits(src1, src2).VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.class_, "C")), Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(CSharpFeaturesResources.struct_, "S")), Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.interface_, "I"))); } [Fact] public void Type_Delete_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { void F() {} }"; var src2 = ReloadableAttributeSrc; GetTopEdits(src1, src2).VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.class_, "C"))); } [Fact] public void Type_Partial_DeleteDeclaration() { var srcA1 = "partial class C { void F() {} void M() { } }"; var srcB1 = "partial class C { void G() {} }"; var srcA2 = ""; var srcB2 = "partial class C { void G() {} void M() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.method, "C.F()")) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("M")), }) }); } [Fact] public void Type_Partial_InsertFirstDeclaration() { var src1 = ""; var src2 = "partial class C { void F() {} }"; GetTopEdits(src1, src2).VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C"), preserveLocalVariables: false) }); } [Fact] public void Type_Partial_InsertSecondDeclaration() { var srcA1 = "partial class C { void F() {} }"; var srcB1 = ""; var srcA2 = "partial class C { void F() {} }"; var srcB2 = "partial class C { void G() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").GetMember("G"), preserveLocalVariables: false) }), }); } [Fact] public void Type_Partial_Reloadable() { var srcA1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { void F() {} }"; var srcB1 = ""; var srcA2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { void F() {} }"; var srcB2 = "partial class C { void G() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C") }), }); } [Fact] public void Type_DeleteInsert() { var srcA1 = @" class C { void F() {} } struct S { void F() {} } interface I { void F() {} } "; var srcB1 = ""; var srcA2 = srcB1; var srcB2 = srcA1; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember("F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("F")), }) }); } [Fact] public void Type_DeleteInsert_Reloadable() { var srcA1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { void F() {} }"; var srcB1 = ""; var srcA2 = ReloadableAttributeSrc; var srcB2 = "[CreateNewOnMetadataUpdate]class C { void F() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C")), }) }); } [Fact] public void Type_NonInsertableMembers_DeleteInsert() { var srcA1 = @" abstract class C { public abstract void AbstractMethod(); public virtual void VirtualMethod() {} public override string ToString() => null; public void I.G() {} } interface I { void G(); void F() {} } "; var srcB1 = ""; var srcA2 = srcB1; var srcB2 = srcA1; // TODO: The methods without bodies do not need to be updated. EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("AbstractMethod")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("VirtualMethod")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("ToString")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("I.G")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("G")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("F")), }) }); } [Fact] public void Type_Attribute_NonInsertableMembers_DeleteInsert() { var srcA1 = @" abstract class C { public abstract void AbstractMethod(); public virtual void VirtualMethod() {} public override string ToString() => null; public void I.G() {} } interface I { void G(); void F() {} } "; var srcB1 = ""; var srcA2 = ""; var srcB2 = @" abstract class C { [System.Obsolete]public abstract void AbstractMethod(); public virtual void VirtualMethod() {} public override string ToString() => null; public void I.G() {} } interface I { [System.Obsolete]void G(); void F() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("AbstractMethod")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("VirtualMethod")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("ToString")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("I.G")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("G")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("F")), }) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Type_DeleteInsert_DataMembers() { var srcA1 = @" class C { public int x = 1; public int y = 2; public int P { get; set; } = 3; public event System.Action E = new System.Action(null); } "; var srcB1 = ""; var srcA2 = ""; var srcB2 = @" class C { public int x = 1; public int y = 2; public int P { get; set; } = 3; public event System.Action E = new System.Action(null); } "; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true), }) }); } [Fact] public void Type_DeleteInsert_DataMembers_PartialSplit() { var srcA1 = @" class C { public int x = 1; public int y = 2; public int P { get; set; } = 3; } "; var srcB1 = ""; var srcA2 = @" partial class C { public int x = 1; public int y = 2; } "; var srcB2 = @" partial class C { public int P { get; set; } = 3; } "; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true), }) }); } [Fact] public void Type_DeleteInsert_DataMembers_PartialMerge() { var srcA1 = @" partial class C { public int x = 1; public int y = 2; } "; var srcB1 = @" partial class C { public int P { get; set; } = 3; }"; var srcA2 = @" class C { public int x = 1; public int y = 2; public int P { get; set; } = 3; } "; var srcB2 = @" "; // note that accessors are not updated since they do not have bodies EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true), }), DocumentResults() }); } #endregion #region Records [Fact] public void Record_Partial_MovePrimaryConstructor() { var src1 = @" partial record C { } partial record C(int X);"; var src2 = @" partial record C(int X); partial record C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_Name_Update() { var src1 = "record C { }"; var src2 = "record D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [record C { }]@0 -> [record D { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "record D", CSharpFeaturesResources.record_)); } [Fact] public void RecordStruct_NoModifiers_Insert() { var src1 = ""; var src2 = "record struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void RecordStruct_AddField() { var src1 = @" record struct C(int X) { }"; var src2 = @" record struct C(int X) { private int _y = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoStruct, "_y = 0", FeaturesResources.field, CSharpFeaturesResources.record_struct)); } [Fact] public void RecordStruct_AddProperty() { var src1 = @" record struct C(int X) { }"; var src2 = @" record struct C(int X) { public int Y { get; set; } = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoStruct, "public int Y { get; set; } = 0;", FeaturesResources.auto_property, CSharpFeaturesResources.record_struct)); } [Fact] public void Record_NoModifiers_Insert() { var src1 = ""; var src2 = "record C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_NoModifiers_IntoNamespace_Insert() { var src1 = "namespace N { }"; var src2 = "namespace N { record C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_NoModifiers_IntoType_Insert() { var src1 = "struct N { }"; var src2 = "struct N { record C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_BaseTypeUpdate1() { var src1 = "record C { }"; var src2 = "record C : D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [record C { }]@0 -> [record C : D { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "record C", CSharpFeaturesResources.record_)); } [Fact] public void Record_BaseTypeUpdate2() { var src1 = "record C : D1 { }"; var src2 = "record C : D2 { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [record C : D1 { }]@0 -> [record C : D2 { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "record C", CSharpFeaturesResources.record_)); } [Fact] public void Record_BaseInterfaceUpdate1() { var src1 = "record C { }"; var src2 = "record C : IDisposable { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [record C { }]@0 -> [record C : IDisposable { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "record C", CSharpFeaturesResources.record_)); } [Fact] public void Record_BaseInterfaceUpdate2() { var src1 = "record C : IGoo, IBar { }"; var src2 = "record C : IGoo { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [record C : IGoo, IBar { }]@0 -> [record C : IGoo { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "record C", CSharpFeaturesResources.record_)); } [Fact] public void Record_BaseInterfaceUpdate3() { var src1 = "record C : IGoo, IBar { }"; var src2 = "record C : IBar, IGoo { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [record C : IGoo, IBar { }]@0 -> [record C : IBar, IGoo { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "record C", CSharpFeaturesResources.record_)); } [Fact] public void RecordInsert_AbstractVirtualOverride() { var src1 = ""; var src2 = @" public abstract record C<T> { public abstract void F(); public virtual void G() {} public override void H() {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_PrintMembers() { var src1 = "record C { }"; var src2 = @" record C { protected virtual bool PrintMembers(System.Text.StringBuilder builder) { return true; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers"))); edits.VerifyRudeDiagnostics(); } [Fact] public void RecordStruct_ImplementSynthesized_PrintMembers() { var src1 = "record struct C { }"; var src2 = @" record struct C { private bool PrintMembers(System.Text.StringBuilder builder) { return true; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_WrongParameterName() { // TODO: Remove this requirement with https://github.com/dotnet/roslyn/issues/52563 var src1 = "record C { }"; var src2 = @" record C { protected virtual bool PrintMembers(System.Text.StringBuilder sb) { return false; } public virtual bool Equals(C rhs) { return false; } protected C(C other) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ExplicitRecordMethodParameterNamesMustMatch, "protected virtual bool PrintMembers(System.Text.StringBuilder sb)", "PrintMembers(System.Text.StringBuilder builder)"), Diagnostic(RudeEditKind.ExplicitRecordMethodParameterNamesMustMatch, "public virtual bool Equals(C rhs)", "Equals(C other)"), Diagnostic(RudeEditKind.ExplicitRecordMethodParameterNamesMustMatch, "protected C(C other)", "C(C original)")); } [Fact] public void Record_ImplementSynthesized_ToString() { var src1 = "record C { }"; var src2 = @" record C { public override string ToString() { return ""R""; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.ToString"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_UnImplementSynthesized_ToString() { var src1 = @" record C { public override string ToString() { return ""R""; } }"; var src2 = "record C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.ToString"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddProperty_Primary() { var src1 = "record C(int X);"; var src2 = "record C(int X, int Y);"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "int Y", FeaturesResources.parameter)); } [Fact] public void Record_AddProperty_NotPrimary() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int Y { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.Y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddProperty_NotPrimary_WithConstructor() { var src1 = @" record C(int X) { public C(string fromAString) { } }"; var src2 = @" record C(int X) { public int Y { get; set; } public C(string fromAString) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.Y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddProperty_NotPrimary_WithExplicitMembers() { var src1 = @" record C(int X) { protected virtual bool PrintMembers(System.Text.StringBuilder builder) { return false; } public override int GetHashCode() { return 0; } public virtual bool Equals(C other) { return false; } public C(C original) { } }"; var src2 = @" record C(int X) { public int Y { get; set; } protected virtual bool PrintMembers(System.Text.StringBuilder builder) { return false; } public override int GetHashCode() { return 0; } public virtual bool Equals(C other) { return false; } public C(C original) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.Y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddProperty_NotPrimary_WithInitializer() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int Y { get; set; } = 1; }"; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.Y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddField() { var src1 = "record C(int X) { }"; var src2 = "record C(int X) { private int _y; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C._y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddField_WithExplicitMembers() { var src1 = @" record C(int X) { public C(C other) { } }"; var src2 = @" record C(int X) { private int _y; public C(C other) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C._y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddField_WithInitializer() { var src1 = "record C(int X) { }"; var src2 = "record C(int X) { private int _y = 1; }"; var syntaxMap = GetSyntaxMap(src1, src2); var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C._y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddField_WithExistingInitializer() { var src1 = "record C(int X) { private int _y = <N:0.0>1</N:0.0>; }"; var src2 = "record C(int X) { private int _y = <N:0.0>1</N:0.0>; private int _z; }"; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C._z")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), syntaxMap[0]), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddField_WithInitializerAndExistingInitializer() { var src1 = "record C(int X) { private int _y = <N:0.0>1</N:0.0>; }"; var src2 = "record C(int X) { private int _y = <N:0.0>1</N:0.0>; private int _z = 1; }"; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C._z")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), syntaxMap[0]), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_DeleteField() { var src1 = "record C(int X) { private int _y; }"; var src2 = "record C(int X) { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.Delete, "record C", DeletedSymbolDisplay(FeaturesResources.field, "_y"))); } [Fact] public void Record_DeleteProperty_Primary() { var src1 = "record C(int X, int Y) { }"; var src2 = "record C(int X) { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.Delete, "record C", DeletedSymbolDisplay(FeaturesResources.parameter, "int Y"))); } [Fact] public void Record_DeleteProperty_NotPrimary() { var src1 = "record C(int X) { public int P { get; set; } }"; var src2 = "record C(int X) { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "record C", DeletedSymbolDisplay(FeaturesResources.auto_property, "P"))); } [Fact] public void Record_ImplementSynthesized_Property() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int X { get; init; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_Property_WithBody() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int X { get { return 4; } init { throw null; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_Property_WithExpressionBody() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int X { get => 4; init => throw null; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_Property_InitToSet() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int X { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ImplementRecordParameterWithSet, "public int X", "X")); } [Fact] public void Record_ImplementSynthesized_Property_MakeReadOnly() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int X { get; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ImplementRecordParameterAsReadOnly, "public int X", "X")); } [Fact] public void Record_UnImplementSynthesized_Property() { var src1 = @" record C(int X) { public int X { get; init; } }"; var src2 = "record C(int X);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_UnImplementSynthesized_Property_WithExpressionBody() { var src1 = @" record C(int X) { public int X { get => 4; init => throw null; } }"; var src2 = "record C(int X);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_UnImplementSynthesized_Property_WithBody() { var src1 = @" record C(int X) { public int X { get { return 4; } init { } } }"; var src2 = "record C(int X);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_Property_Partial() { var srcA1 = @"partial record C(int X);"; var srcB1 = @"partial record C;"; var srcA2 = @"partial record C(int X);"; var srcB2 = @" partial record C { public int X { get; init; } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), partialType: "C", preserveLocalVariables: true) }) }); } [Fact] public void Record_UnImplementSynthesized_Property_Partial() { var srcA1 = @"partial record C(int X);"; var srcB1 = @" partial record C { public int X { get; init; } }"; var srcA2 = @"partial record C(int X);"; var srcB2 = @"partial record C;"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), partialType: "C", preserveLocalVariables: true) }) }); } [Fact] public void Record_ImplementSynthesized_Property_Partial_WithBody() { var srcA1 = @"partial record C(int X);"; var srcB1 = @"partial record C;"; var srcA2 = @"partial record C(int X);"; var srcB2 = @" partial record C { public int X { get { return 4; } init { throw null; } } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), partialType : "C", preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C")) }) }); } [Fact] public void Record_UnImplementSynthesized_Property_Partial_WithBody() { var srcA1 = @"partial record C(int X);"; var srcB1 = @" partial record C { public int X { get { return 4; } init { throw null; } } }"; var srcA2 = @"partial record C(int X);"; var srcB2 = @"partial record C;"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), partialType : "C", preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C")) }) }); } [Fact] public void Record_MoveProperty_Partial() { var srcA1 = @" partial record C(int X) { public int Y { get; init; } }"; var srcB1 = @" partial record C; "; var srcA2 = @" partial record C(int X); "; var srcB2 = @" partial record C { public int Y { get; init; } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.Y").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.Y").SetMethod) }), }); } [Fact] public void Record_UnImplementSynthesized_Property_WithInitializer() { var src1 = @" record C(int X) { public int X { get; init; } = 1; }"; var src2 = "record C(int X);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_UnImplementSynthesized_Property_WithInitializerMatchingCompilerGenerated() { var src1 = @" record C(int X) { public int X { get; init; } = X; }"; var src2 = "record C(int X);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_Property_Delete_NotPrimary() { var src1 = @" record C(int X) { public int Y { get; init; } }"; var src2 = "record C(int X);"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "record C", DeletedSymbolDisplay(FeaturesResources.auto_property, "Y"))); } [Fact] public void Record_PropertyInitializer_Update_NotPrimary() { var src1 = "record C { int X { get; } = 0; }"; var src2 = "record C { int X { get; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Length == 0), preserveLocalVariables: true)); } [Fact] public void Record_PropertyInitializer_Update_Primary() { var src1 = "record C(int X) { int X { get; } = 0; }"; var src2 = "record C(int X) { int X { get; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); } #endregion #region Enums [Fact] public void Enum_NoModifiers_Insert() { var src1 = ""; var src2 = "enum C { A }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Enum_NoModifiers_IntoNamespace_Insert() { var src1 = "namespace N { }"; var src2 = "namespace N { enum C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Enum_NoModifiers_IntoType_Insert() { var src1 = "struct N { }"; var src2 = "struct N { enum C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Enum_Attribute_Insert() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "enum E { }"; var src2 = attribute + "[A]enum E { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum E { }]@48 -> [[A]enum E { }]@48"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "enum E", FeaturesResources.enum_)); } [Fact] public void Enum_Member_Attribute_Delete() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "enum E { [A]X }"; var src2 = attribute + "enum E { X }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]X]@57 -> [X]@57"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "X", FeaturesResources.enum_value)); } [Fact] public void Enum_Member_Attribute_Insert() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "enum E { X }"; var src2 = attribute + "enum E { [A]X }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [X]@57 -> [[A]X]@57"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "[A]X", FeaturesResources.enum_value)); } [Fact] public void Enum_Member_Attribute_Update() { var attribute = "public class A1Attribute : System.Attribute { }\n\n" + "public class A2Attribute : System.Attribute { }\n\n"; var src1 = attribute + "enum E { [A1]X }"; var src2 = attribute + "enum E { [A2]X }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A1]X]@107 -> [[A2]X]@107"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "[A2]X", FeaturesResources.enum_value)); } [Fact] public void Enum_Member_Attribute_InsertDeleteAndUpdate() { var srcA1 = ""; var srcB1 = "enum N { A = 1 }"; var srcA2 = "enum N { [System.Obsolete]A = 1 }"; var srcB2 = ""; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("N.A")) }), DocumentResults() }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Enum_Rename() { var src1 = "enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Colors { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum Color { Red = 1, Blue = 2, }]@0 -> [enum Colors { Red = 1, Blue = 2, }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "enum Colors", FeaturesResources.enum_)); } [Fact] public void Enum_BaseType_Add() { var src1 = "enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Color : ushort { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color { Red = 1, Blue = 2, }]@0 -> [enum Color : ushort { Red = 1, Blue = 2, }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.EnumUnderlyingTypeUpdate, "enum Color", FeaturesResources.enum_)); } [Fact] public void Enum_BaseType_Add_Unchanged() { var src1 = "enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Color : int { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color { Red = 1, Blue = 2, }]@0 -> [enum Color : int { Red = 1, Blue = 2, }]@0"); edits.VerifySemantics(); } [Fact] public void Enum_BaseType_Update() { var src1 = "enum Color : ushort { Red = 1, Blue = 2, }"; var src2 = "enum Color : long { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color : ushort { Red = 1, Blue = 2, }]@0 -> [enum Color : long { Red = 1, Blue = 2, }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.EnumUnderlyingTypeUpdate, "enum Color", FeaturesResources.enum_)); } [Fact] public void Enum_BaseType_Delete_Unchanged() { var src1 = "enum Color : int { Red = 1, Blue = 2, }"; var src2 = "enum Color { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color : int { Red = 1, Blue = 2, }]@0 -> [enum Color { Red = 1, Blue = 2, }]@0"); edits.VerifySemantics(); } [Fact] public void Enum_BaseType_Delete_Changed() { var src1 = "enum Color : ushort { Red = 1, Blue = 2, }"; var src2 = "enum Color { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color : ushort { Red = 1, Blue = 2, }]@0 -> [enum Color { Red = 1, Blue = 2, }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.EnumUnderlyingTypeUpdate, "enum Color", FeaturesResources.enum_)); } [Fact] public void EnumAccessibilityChange() { var src1 = "public enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Color { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public enum Color { Red = 1, Blue = 2, }]@0 -> [enum Color { Red = 1, Blue = 2, }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "enum Color", FeaturesResources.enum_)); } [Fact] public void EnumAccessibilityNoChange() { var src1 = "internal enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Color { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Fact] public void EnumInitializerUpdate() { var src1 = "enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Color { Red = 1, Blue = 3, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Blue = 2]@22 -> [Blue = 3]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, "Blue = 3", FeaturesResources.enum_value)); } [Fact] public void EnumInitializerUpdate2() { var src1 = "enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Color { Red = 1 << 0, Blue = 2 << 1, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [Red = 1]@13 -> [Red = 1 << 0]@13", "Update [Blue = 2]@22 -> [Blue = 2 << 1]@27"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, "Blue = 2 << 1", FeaturesResources.enum_value)); } [Fact] public void EnumInitializerUpdate3() { var src1 = "enum Color { Red = int.MinValue }"; var src2 = "enum Color { Red = int.MaxValue }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [Red = int.MinValue]@13 -> [Red = int.MaxValue]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, "Red = int.MaxValue", FeaturesResources.enum_value)); } [Fact] public void EnumInitializerUpdate_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]enum Color { Red = 1 }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]enum Color { Red = 2 }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [Red = 1]@185 -> [Red = 2]@185"); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("Color"))); } [Fact] public void EnumInitializerAdd() { var src1 = "enum Color { Red, }"; var src2 = "enum Color { Red = 1, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Red]@13 -> [Red = 1]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, "Red = 1", FeaturesResources.enum_value)); } [Fact] public void EnumInitializerDelete() { var src1 = "enum Color { Red = 1, }"; var src2 = "enum Color { Red, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Red = 1]@13 -> [Red]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, "Red", FeaturesResources.enum_value)); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916")] [Fact] public void EnumMemberAdd() { var src1 = "enum Color { Red }"; var src2 = "enum Color { Red, Blue}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum Color { Red }]@0 -> [enum Color { Red, Blue}]@0", "Insert [Blue]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "Blue", FeaturesResources.enum_value)); } [Fact] public void EnumMemberAdd2() { var src1 = "enum Color { Red, }"; var src2 = "enum Color { Red, Blue}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [Blue]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "Blue", FeaturesResources.enum_value)); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916")] [Fact] public void EnumMemberAdd3() { var src1 = "enum Color { Red, }"; var src2 = "enum Color { Red, Blue,}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color { Red, }]@0 -> [enum Color { Red, Blue,}]@0", "Insert [Blue]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "Blue", FeaturesResources.enum_value)); } [Fact] public void EnumMemberUpdate() { var src1 = "enum Color { Red }"; var src2 = "enum Color { Orange }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Red]@13 -> [Orange]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "Orange", FeaturesResources.enum_value)); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916")] [Fact] public void EnumMemberDelete() { var src1 = "enum Color { Red, Blue}"; var src2 = "enum Color { Red }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum Color { Red, Blue}]@0 -> [enum Color { Red }]@0", "Delete [Blue]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "enum Color", DeletedSymbolDisplay(FeaturesResources.enum_value, "Blue"))); } [Fact] public void EnumMemberDelete2() { var src1 = "enum Color { Red, Blue}"; var src2 = "enum Color { Red, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [Blue]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "enum Color", DeletedSymbolDisplay(FeaturesResources.enum_value, "Blue"))); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916"), WorkItem(793197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/793197")] [Fact] public void EnumTrailingCommaAdd() { var src1 = "enum Color { Red }"; var src2 = "enum Color { Red, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum Color { Red }]@0 -> [enum Color { Red, }]@0"); edits.VerifySemantics(ActiveStatementsDescription.Empty, NoSemanticEdits); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916"), WorkItem(793197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/793197")] [Fact] public void EnumTrailingCommaAdd_WithInitializer() { var src1 = "enum Color { Red = 1 }"; var src2 = "enum Color { Red = 1, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum Color { Red = 1 }]@0 -> [enum Color { Red = 1, }]@0"); edits.VerifySemantics(ActiveStatementsDescription.Empty, NoSemanticEdits); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916"), WorkItem(793197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/793197")] [Fact] public void EnumTrailingCommaDelete() { var src1 = "enum Color { Red, }"; var src2 = "enum Color { Red }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color { Red, }]@0 -> [enum Color { Red }]@0"); edits.VerifySemantics(ActiveStatementsDescription.Empty, NoSemanticEdits); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916"), WorkItem(793197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/793197")] [Fact] public void EnumTrailingCommaDelete_WithInitializer() { var src1 = "enum Color { Red = 1, }"; var src2 = "enum Color { Red = 1 }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color { Red = 1, }]@0 -> [enum Color { Red = 1 }]@0"); edits.VerifySemantics(ActiveStatementsDescription.Empty, NoSemanticEdits); } #endregion #region Delegates [Fact] public void Delegates_NoModifiers_Insert() { var src1 = ""; var src2 = "delegate void D();"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_NoModifiers_IntoNamespace_Insert() { var src1 = "namespace N { }"; var src2 = "namespace N { delegate void D(); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_NoModifiers_IntoType_Insert() { var src1 = "class C { }"; var src2 = "class C { delegate void D(); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_Public_IntoType_Insert() { var src1 = "class C { }"; var src2 = "class C { public delegate void D(); }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [public delegate void D();]@10", "Insert [()]@32"); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_Generic_Insert() { var src1 = "class C { }"; var src2 = "class C { private delegate void D<T>(T a); }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [private delegate void D<T>(T a);]@10", "Insert [<T>]@33", "Insert [(T a)]@36", "Insert [T]@34", "Insert [T a]@37"); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_Delete() { var src1 = "class C { private delegate void D(); }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [private delegate void D();]@10", "Delete [()]@33"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.delegate_, "D"))); } [Fact] public void Delegates_Rename() { var src1 = "public delegate void D();"; var src2 = "public delegate void Z();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate void D();]@0 -> [public delegate void Z();]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "public delegate void Z()", FeaturesResources.delegate_)); } [Fact] public void Delegates_Accessibility_Update() { var src1 = "public delegate void D();"; var src2 = "private delegate void D();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate void D();]@0 -> [private delegate void D();]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "private delegate void D()", FeaturesResources.delegate_)); } [Fact] public void Delegates_ReturnType_Update() { var src1 = "public delegate int D();"; var src2 = "public delegate void D();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate int D();]@0 -> [public delegate void D();]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "public delegate void D()", FeaturesResources.delegate_)); } [Fact] public void Delegates_ReturnType_AddAttribute() { var attribute = "public class A : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D(int a);"; var src2 = attribute + "[return: A]public delegate int D(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate int D(int a);]@39 -> [[return: A]public delegate int D(int a);]@39"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.Invoke")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.BeginInvoke")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Delegates_Parameter_Insert() { var src1 = "public delegate int D();"; var src2 = "public delegate int D(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [int a]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "int a", FeaturesResources.parameter)); } [Fact] public void Delegates_Parameter_Insert_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]public delegate int D();"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]internal delegate bool D(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("D"))); } [Fact] public void Delegates_Parameter_Delete() { var src1 = "public delegate int D(int a);"; var src2 = "public delegate int D();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [int a]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "public delegate int D()", DeletedSymbolDisplay(FeaturesResources.parameter, "int a"))); } [Fact] public void Delegates_Parameter_Rename() { var src1 = "public delegate int D(int a);"; var src2 = "public delegate int D(int b);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@22 -> [int b]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "int b", FeaturesResources.parameter)); } [Fact] public void Delegates_Parameter_Update() { var src1 = "public delegate int D(int a);"; var src2 = "public delegate int D(byte a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@22 -> [byte a]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "byte a", FeaturesResources.parameter)); } [Fact] public void Delegates_Parameter_AddAttribute_NotSupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D(int a);"; var src2 = attribute + "public delegate int D([A]int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@70 -> [[A]int a]@70"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Delegates_Parameter_AddAttribute() { var attribute = "public class A : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D(int a);"; var src2 = attribute + "public delegate int D([A]int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@61 -> [[A]int a]@61"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.Invoke")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.BeginInvoke")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Delegates_TypeParameter_Insert() { var src1 = "public delegate int D();"; var src2 = "public delegate int D<T>();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [<T>]@21", "Insert [T]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "T", FeaturesResources.type_parameter)); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/54881")] [WorkItem(54881, "https://github.com/dotnet/roslyn/issues/54881")] public void Delegates_TypeParameter_Insert_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]public delegate int D<out T>();"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]internal delegate bool D<in T, out S>(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("D"))); } [Fact] public void Delegates_TypeParameter_Delete() { var src1 = "public delegate int D<T>();"; var src2 = "public delegate int D();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [<T>]@21", "Delete [T]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "public delegate int D()", DeletedSymbolDisplay(FeaturesResources.type_parameter, "T"))); } [Fact] public void Delegates_TypeParameter_Rename() { var src1 = "public delegate int D<T>();"; var src2 = "public delegate int D<S>();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [T]@22 -> [S]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "S", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "S")); } [Fact] public void Delegates_TypeParameter_Variance1() { var src1 = "public delegate int D<T>();"; var src2 = "public delegate int D<in T>();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [T]@22 -> [in T]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.VarianceUpdate, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void Delegates_TypeParameter_Variance2() { var src1 = "public delegate int D<out T>();"; var src2 = "public delegate int D<T>();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [out T]@22 -> [T]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.VarianceUpdate, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void Delegates_TypeParameter_Variance3() { var src1 = "public delegate int D<out T>();"; var src2 = "public delegate int D<in T>();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [out T]@22 -> [in T]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.VarianceUpdate, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void Delegates_TypeParameter_AddAttribute() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D<T>();"; var src2 = attribute + "public delegate int D<[A]T>();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [T]@70 -> [[A]T]@70"); edits.VerifyRudeDiagnostics( EditAndContinueTestHelpers.Net6RuntimeCapabilities, Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void Delegates_Attribute_Add_NotSupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D(int a);"; var src2 = attribute + "[A]public delegate int D(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate int D(int a);]@48 -> [[A]public delegate int D(int a);]@48"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "public delegate int D(int a)", FeaturesResources.delegate_)); } [Fact] public void Delegates_Attribute_Add() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D(int a);"; var src2 = attribute + "[A]public delegate int D(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate int D(int a);]@48 -> [[A]public delegate int D(int a);]@48"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Delegates_Attribute_Add_WithReturnTypeAttribute() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D(int a);"; var src2 = attribute + "[return: A][A]public delegate int D(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate int D(int a);]@48 -> [[return: A][A]public delegate int D(int a);]@48"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.Invoke")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.BeginInvoke")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Delegates_ReadOnlyRef_Parameter_InsertWhole() { var src1 = ""; var src2 = "public delegate int D(in int b);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [public delegate int D(in int b);]@0", "Insert [(in int b)]@21", "Insert [in int b]@22"); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_ReadOnlyRef_Parameter_InsertParameter() { var src1 = "public delegate int D();"; var src2 = "public delegate int D(in int b);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [in int b]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "in int b", FeaturesResources.parameter)); } [Fact] public void Delegates_ReadOnlyRef_Parameter_Update() { var src1 = "public delegate int D(int b);"; var src2 = "public delegate int D(in int b);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int b]@22 -> [in int b]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "in int b", FeaturesResources.parameter)); } [Fact] public void Delegates_ReadOnlyRef_ReturnType_Insert() { var src1 = ""; var src2 = "public delegate ref readonly int D();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [public delegate ref readonly int D();]@0", "Insert [()]@34"); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_ReadOnlyRef_ReturnType_Update() { var src1 = "public delegate int D();"; var src2 = "public delegate ref readonly int D();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate int D();]@0 -> [public delegate ref readonly int D();]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "public delegate ref readonly int D()", FeaturesResources.delegate_)); } #endregion #region Nested Types [Fact] public void NestedClass_ClassMove1() { var src1 = @"class C { class D { } }"; var src2 = @"class C { } class D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Move [class D { }]@10 -> @12"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "class D", FeaturesResources.class_)); } [Fact] public void NestedClass_ClassMove2() { var src1 = @"class C { class D { } class E { } class F { } }"; var src2 = @"class C { class D { } class F { } } class E { } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Move [class E { }]@23 -> @37"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "class E", FeaturesResources.class_)); } [Fact] public void NestedClass_ClassInsertMove1() { var src1 = @"class C { class D { } }"; var src2 = @"class C { class E { class D { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [class E { class D { } }]@10", "Move [class D { }]@10 -> @20"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "class D", FeaturesResources.class_)); } [Fact] public void NestedClass_Insert1() { var src1 = @"class C { }"; var src2 = @"class C { class D { class E { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [class D { class E { } }]@10", "Insert [class E { }]@20"); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedClass_Insert2() { var src1 = @"class C { }"; var src2 = @"class C { protected class D { public class E { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [protected class D { public class E { } }]@10", "Insert [public class E { }]@30"); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedClass_Insert3() { var src1 = @"class C { }"; var src2 = @"class C { private class D { public class E { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [private class D { public class E { } }]@10", "Insert [public class E { }]@28"); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedClass_Insert4() { var src1 = @"class C { }"; var src2 = @"class C { private class D { public D(int a, int b) { } public int P { get; set; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [private class D { public D(int a, int b) { } public int P { get; set; } }]@10", "Insert [public D(int a, int b) { }]@28", "Insert [public int P { get; set; }]@55", "Insert [(int a, int b)]@36", "Insert [{ get; set; }]@68", "Insert [int a]@37", "Insert [int b]@44", "Insert [get;]@70", "Insert [set;]@75"); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedClass_Insert_ReloadableIntoReloadable1() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { [CreateNewOnMetadataUpdate]class D { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void NestedClass_Insert_ReloadableIntoReloadable2() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { [CreateNewOnMetadataUpdate]class D { [CreateNewOnMetadataUpdate]class E { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void NestedClass_Insert_ReloadableIntoReloadable3() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { class D { [CreateNewOnMetadataUpdate]class E { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void NestedClass_Insert_ReloadableIntoReloadable4() { var src1 = ReloadableAttributeSrc + "class C { }"; var src2 = ReloadableAttributeSrc + "class C { [CreateNewOnMetadataUpdate]class D { [CreateNewOnMetadataUpdate]class E { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.D"))); } [Fact] public void NestedClass_Insert_Member_Reloadable() { var src1 = ReloadableAttributeSrc + "class C { [CreateNewOnMetadataUpdate]class D { } }"; var src2 = ReloadableAttributeSrc + "class C { [CreateNewOnMetadataUpdate]class D { int x; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C.D"))); } [Fact] public void NestedClass_InsertMemberWithInitializer1() { var src1 = @" class C { }"; var src2 = @" class C { private class D { public int P = 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.D"), preserveLocalVariables: false) }); } [WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] [Fact] public void NestedClass_Insert_PInvoke() { var src1 = @" using System; using System.Runtime.InteropServices; class C { }"; var src2 = @" using System; using System.Runtime.InteropServices; class C { abstract class D { public extern D(); public static extern int P { [DllImport(""msvcrt.dll"")]get; [DllImport(""msvcrt.dll"")]set; } [DllImport(""msvcrt.dll"")] public static extern int puts(string c); [DllImport(""msvcrt.dll"")] public static extern int operator +(D d, D g); [DllImport(""msvcrt.dll"")] public static extern explicit operator int (D d); } } "; var edits = GetTopEdits(src1, src2); // Adding P/Invoke is not supported by the CLR. edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertExtern, "public extern D()", FeaturesResources.constructor), Diagnostic(RudeEditKind.InsertExtern, "public static extern int P", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertExtern, "public static extern int puts(string c)", FeaturesResources.method), Diagnostic(RudeEditKind.InsertExtern, "public static extern int operator +(D d, D g)", FeaturesResources.operator_), Diagnostic(RudeEditKind.InsertExtern, "public static extern explicit operator int (D d)", CSharpFeaturesResources.conversion_operator)); } [WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] [Fact] public void NestedClass_Insert_VirtualAbstract() { var src1 = @" using System; using System.Runtime.InteropServices; class C { }"; var src2 = @" using System; using System.Runtime.InteropServices; class C { abstract class D { public abstract int P { get; } public abstract int this[int i] { get; } public abstract int puts(string c); public virtual event Action E { add { } remove { } } public virtual int Q { get { return 1; } } public virtual int this[string i] { get { return 1; } } public virtual int M(string c) { return 1; } } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedClass_TypeReorder1() { var src1 = @"class C { struct E { } class F { } delegate void D(); interface I {} }"; var src2 = @"class C { class F { } interface I {} delegate void D(); struct E { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [struct E { }]@10 -> @56", "Reorder [interface I {}]@54 -> @22"); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedClass_MethodDeleteInsert() { var src1 = @"public class C { public void goo() {} }"; var src2 = @"public class C { private class D { public void goo() {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [private class D { public void goo() {} }]@17", "Insert [public void goo() {}]@35", "Insert [()]@50", "Delete [public void goo() {}]@17", "Delete [()]@32"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "public class C", DeletedSymbolDisplay(FeaturesResources.method, "goo()"))); } [Fact] public void NestedClass_ClassDeleteInsert() { var src1 = @"public class C { public class X {} }"; var src2 = @"public class C { public class D { public class X {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [public class D { public class X {} }]@17", "Move [public class X {}]@17 -> @34"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "public class X", FeaturesResources.class_)); } /// <summary> /// A new generic type can be added whether it's nested and inherits generic parameters from the containing type, or top-level. /// </summary> [Fact] public void NestedClassGeneric_Insert() { var src1 = @" using System; class C<T> { } "; var src2 = @" using System; class C<T> { class D {} struct S {} enum N {} interface I {} delegate void D(); } class D<T> { } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedEnum_InsertMember() { var src1 = "struct S { enum N { A = 1 } }"; var src2 = "struct S { enum N { A = 1, B = 2 } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum N { A = 1 }]@11 -> [enum N { A = 1, B = 2 }]@11", "Insert [B = 2]@27"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "B = 2", FeaturesResources.enum_value)); } [Fact, WorkItem(50876, "https://github.com/dotnet/roslyn/issues/50876")] public void NestedEnumInPartialType_InsertDelete() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { enum N { A = 1 } }"; var srcA2 = "partial struct S { enum N { A = 1 } }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults() }); } [Fact, WorkItem(50876, "https://github.com/dotnet/roslyn/issues/50876")] public void NestedEnumInPartialType_InsertDeleteAndUpdateMember() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { enum N { A = 1 } }"; var srcA2 = "partial struct S { enum N { A = 2 } }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.InitializerUpdate, "A = 2", FeaturesResources.enum_value), }), DocumentResults() }); } [Fact, WorkItem(50876, "https://github.com/dotnet/roslyn/issues/50876")] public void NestedEnumInPartialType_InsertDeleteAndUpdateBase() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { enum N : uint { A = 1 } }"; var srcA2 = "partial struct S { enum N : int { A = 1 } }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.EnumUnderlyingTypeUpdate, "enum N", FeaturesResources.enum_), }), DocumentResults() }); } [Fact, WorkItem(50876, "https://github.com/dotnet/roslyn/issues/50876")] public void NestedEnumInPartialType_InsertDeleteAndInsertMember() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { enum N { A = 1 } }"; var srcA2 = "partial struct S { enum N { A = 1, B = 2 } }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Insert, "B = 2", FeaturesResources.enum_value) }), DocumentResults() }); } [Fact] public void NestedDelegateInPartialType_InsertDelete() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { delegate void D(); }"; var srcA2 = "partial struct S { delegate void D(); }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( // delegate does not have any user-defined method body and this does not need a PDB update semanticEdits: NoSemanticEdits), DocumentResults() }); } [Fact] public void NestedDelegateInPartialType_InsertDeleteAndChangeParameters() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { delegate void D(); }"; var srcA2 = "partial struct S { delegate void D(int x); }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.ChangingParameterTypes, "delegate void D(int x)", FeaturesResources.delegate_) }), DocumentResults() }); } [Fact] public void NestedDelegateInPartialType_InsertDeleteAndChangeReturnType() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { delegate ref int D(); }"; var srcA2 = "partial struct S { delegate ref readonly int D(); }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.TypeUpdate, "delegate ref readonly int D()", FeaturesResources.delegate_) }), DocumentResults() }); } [Fact] public void NestedDelegateInPartialType_InsertDeleteAndChangeOptionalParameterValue() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { delegate void D(int x = 1); }"; var srcA2 = "partial struct S { delegate void D(int x = 2); }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.InitializerUpdate, "int x = 2", FeaturesResources.parameter) }), DocumentResults() }); } [Fact] public void NestedPartialTypeInPartialType_InsertDeleteAndChange() { var srcA1 = "partial struct S { partial class C { void F1() {} } }"; var srcB1 = "partial struct S { partial class C { void F2(byte x) {} } }"; var srcC1 = "partial struct S { }"; var srcA2 = "partial struct S { partial class C { void F1() {} } }"; var srcB2 = "partial struct S { }"; var srcC2 = "partial struct S { partial class C { void F2(int x) {} } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial struct S", DeletedSymbolDisplay(FeaturesResources.method, "F2(byte x)")) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("S").GetMember<INamedTypeSymbol>("C").GetMember("F2")) }) }); } [Fact] public void Type_Partial_AddMultiple() { var srcA1 = ""; var srcB1 = ""; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C"), partialType: "C") }), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C"), partialType: "C") }), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Type_Partial_InsertDeleteAndChange_Attribute() { var srcA1 = "partial class C { }"; var srcB1 = ""; var srcC1 = "partial class C { }"; var srcA2 = ""; var srcB2 = "[A]partial class C { }"; var srcC2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C"), partialType: "C") }), DocumentResults(), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Type_Partial_InsertDeleteAndChange_TypeParameterAttribute_NotSupportedByRuntime() { var srcA1 = "partial class C<T> { }"; var srcB1 = ""; var srcC1 = "partial class C<T> { }"; var srcA2 = ""; var srcB2 = "partial class C<[A]T> { }"; var srcC2 = "partial class C<T> { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "partial class C<[A]T>"), Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T") }), DocumentResults(), }); } [Fact] public void Type_Partial_InsertDeleteAndChange_Constraint() { var srcA1 = "partial class C<T> { }"; var srcB1 = ""; var srcC1 = "partial class C<T> { }"; var srcA2 = ""; var srcB2 = "partial class C<T> where T : new() { }"; var srcC2 = "partial class C<T> { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "partial class C<T>"), Diagnostic(RudeEditKind.ChangingConstraints, "where T : new()", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "where T : new()") }), DocumentResults(), }); } [Fact] public void Type_Partial_InsertDeleteRefactor() { var srcA1 = "partial class C : I { void F() { } }"; var srcB1 = "[A][B]partial class C : J { void G() { } }"; var srcC1 = ""; var srcD1 = ""; var srcA2 = ""; var srcB2 = ""; var srcC2 = "[A]partial class C : I, J { void F() { } }"; var srcD2 = "[B]partial class C { void G() { } }"; var srcE = "interface I {} interface J {}"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2), GetTopEdits(srcD1, srcD2), GetTopEdits(srcE, srcE) }, new[] { DocumentResults(), DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F")) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("G")) }), DocumentResults(), }); } [Fact] public void Type_Partial_Attribute_AddMultiple() { var attributes = @" class A : System.Attribute {} class B : System.Attribute {} "; var srcA1 = "partial class C { }" + attributes; var srcB1 = "partial class C { }"; var srcA2 = "[A]partial class C { }" + attributes; var srcB2 = "[B]partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C"), partialType: "C") }), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C"), partialType: "C") }), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Type_Partial_InsertDeleteRefactor_AttributeListSplitting() { var srcA1 = "partial class C { void F() { } }"; var srcB1 = "[A,B]partial class C { void G() { } }"; var srcC1 = ""; var srcD1 = ""; var srcA2 = ""; var srcB2 = ""; var srcC2 = "[A]partial class C { void F() { } }"; var srcD2 = "[B]partial class C { void G() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2), GetTopEdits(srcD1, srcD2) }, new[] { DocumentResults(), DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")) }), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.G")) }), }); } [Fact] public void Type_Partial_InsertDeleteChangeMember() { var srcA1 = "partial class C { void F(int y = 1) { } }"; var srcB1 = "partial class C { void G(int x = 1) { } }"; var srcC1 = ""; var srcA2 = ""; var srcB2 = "partial class C { void G(int x = 2) { } }"; var srcC2 = "partial class C { void F(int y = 2) { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.InitializerUpdate, "int x = 2", FeaturesResources.parameter) }), DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.InitializerUpdate, "int y = 2", FeaturesResources.parameter) }), }); } [Fact] public void NestedPartialTypeInPartialType_InsertDeleteAndInsertVirtual() { var srcA1 = "partial interface I { partial class C { virtual void F1() {} } }"; var srcB1 = "partial interface I { partial class C { virtual void F2() {} } }"; var srcC1 = "partial interface I { partial class C { } }"; var srcD1 = "partial interface I { partial class C { } }"; var srcE1 = "partial interface I { }"; var srcF1 = "partial interface I { }"; var srcA2 = "partial interface I { partial class C { } }"; var srcB2 = ""; var srcC2 = "partial interface I { partial class C { virtual void F1() {} } }"; // move existing virtual into existing partial decl var srcD2 = "partial interface I { partial class C { virtual void N1() {} } }"; // insert new virtual into existing partial decl var srcE2 = "partial interface I { partial class C { virtual void F2() {} } }"; // move existing virtual into a new partial decl var srcF2 = "partial interface I { partial class C { virtual void N2() {} } }"; // insert new virtual into new partial decl EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2), GetTopEdits(srcD1, srcD2), GetTopEdits(srcE1, srcE2), GetTopEdits(srcF1, srcF2) }, new[] { // A DocumentResults(), // B DocumentResults(), // C DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember<INamedTypeSymbol>("C").GetMember("F1")) }), // D DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.InsertVirtual, "virtual void N1()", FeaturesResources.method) }), // E DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember<INamedTypeSymbol>("C").GetMember("F2")) }), // F DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.InsertVirtual, "virtual void N2()", FeaturesResources.method) }), }); } #endregion #region Namespaces [Fact] public void Namespace_Insert() { var src1 = @""; var src2 = @"namespace C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [namespace C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "namespace C", FeaturesResources.namespace_)); } [Fact] public void Namespace_InsertNested() { var src1 = @"namespace C { }"; var src2 = @"namespace C { namespace D { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [namespace D { }]@14"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "namespace D", FeaturesResources.namespace_)); } [Fact] public void Namespace_DeleteNested() { var src1 = @"namespace C { namespace D { } }"; var src2 = @"namespace C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [namespace D { }]@14"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "namespace C", FeaturesResources.namespace_)); } [Fact] public void Namespace_Move() { var src1 = @"namespace C { namespace D { } }"; var src2 = @"namespace C { } namespace D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Move [namespace D { }]@14 -> @16"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "namespace D", FeaturesResources.namespace_)); } [Fact] public void Namespace_Reorder1() { var src1 = @"namespace C { namespace D { } class T { } namespace E { } }"; var src2 = @"namespace C { namespace E { } class T { } namespace D { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [class T { }]@30 -> @30", "Reorder [namespace E { }]@42 -> @14"); edits.VerifyRudeDiagnostics(); } [Fact] public void Namespace_Reorder2() { var src1 = @"namespace C { namespace D1 { } namespace D2 { } namespace D3 { } class T { } namespace E { } }"; var src2 = @"namespace C { namespace E { } class T { } namespace D1 { } namespace D2 { } namespace D3 { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [class T { }]@65 -> @65", "Reorder [namespace E { }]@77 -> @14"); edits.VerifyRudeDiagnostics(); } [Fact] public void Namespace_FileScoped_Insert() { var src1 = @""; var src2 = @"namespace C;"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [namespace C;]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "namespace C", FeaturesResources.namespace_)); } [Fact] public void Namespace_FileScoped_Delete() { var src1 = @"namespace C;"; var src2 = @""; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [namespace C;]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, null, FeaturesResources.namespace_)); } #endregion #region Members [Fact] public void PartialMember_DeleteInsert_SingleDocument() { var src1 = @" using System; partial class C { void M() {} int P1 { get; set; } int P2 { get => 1; set {} } int this[int i] { get => 1; set {} } int this[byte i] { get => 1; set {} } event Action E { add {} remove {} } event Action EF; int F1; int F2; } partial class C { } "; var src2 = @" using System; partial class C { } partial class C { void M() {} int P1 { get; set; } int P2 { get => 1; set {} } int this[int i] { get => 1; set {} } int this[byte i] { get => 1; set {} } event Action E { add {} remove {} } event Action EF; int F1, F2; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [void M() {}]@68", "Insert [int P1 { get; set; }]@85", "Insert [int P2 { get => 1; set {} }]@111", "Insert [int this[int i] { get => 1; set {} }]@144", "Insert [int this[byte i] { get => 1; set {} }]@186", "Insert [event Action E { add {} remove {} }]@229", "Insert [event Action EF;]@270", "Insert [int F1, F2;]@292", "Insert [()]@74", "Insert [{ get; set; }]@92", "Insert [{ get => 1; set {} }]@118", "Insert [[int i]]@152", "Insert [{ get => 1; set {} }]@160", "Insert [[byte i]]@194", "Insert [{ get => 1; set {} }]@203", "Insert [{ add {} remove {} }]@244", "Insert [Action EF]@276", "Insert [int F1, F2]@292", "Insert [get;]@94", "Insert [set;]@99", "Insert [get => 1;]@120", "Insert [set {}]@130", "Insert [int i]@153", "Insert [get => 1;]@162", "Insert [set {}]@172", "Insert [byte i]@195", "Insert [get => 1;]@205", "Insert [set {}]@215", "Insert [add {}]@246", "Insert [remove {}]@253", "Insert [EF]@283", "Insert [F1]@296", "Insert [F2]@300", "Delete [void M() {}]@43", "Delete [()]@49", "Delete [int P1 { get; set; }]@60", "Delete [{ get; set; }]@67", "Delete [get;]@69", "Delete [set;]@74", "Delete [int P2 { get => 1; set {} }]@86", "Delete [{ get => 1; set {} }]@93", "Delete [get => 1;]@95", "Delete [set {}]@105", "Delete [int this[int i] { get => 1; set {} }]@119", "Delete [[int i]]@127", "Delete [int i]@128", "Delete [{ get => 1; set {} }]@135", "Delete [get => 1;]@137", "Delete [set {}]@147", "Delete [int this[byte i] { get => 1; set {} }]@161", "Delete [[byte i]]@169", "Delete [byte i]@170", "Delete [{ get => 1; set {} }]@178", "Delete [get => 1;]@180", "Delete [set {}]@190", "Delete [event Action E { add {} remove {} }]@204", "Delete [{ add {} remove {} }]@219", "Delete [add {}]@221", "Delete [remove {}]@228", "Delete [event Action EF;]@245", "Delete [Action EF]@251", "Delete [EF]@258", "Delete [int F1;]@267", "Delete [int F1]@267", "Delete [F1]@271", "Delete [int F2;]@280", "Delete [int F2]@280", "Delete [F2]@284"); EditAndContinueValidation.VerifySemantics( new[] { edits }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("M"), preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P1").GetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P1").SetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P2").GetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P2").SetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.GetParameters().Single().Type.Name == "Int32").GetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.GetParameters().Single().Type.Name == "Int32").SetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.GetParameters().Single().Type.Name == "Byte").GetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.GetParameters().Single().Type.Name == "Byte").SetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E").AddMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E").RemoveMethod, preserveLocalVariables: false), }) }); } [Fact] public void PartialMember_InsertDelete_MultipleDocuments() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { void F() {} }"; var srcA2 = "partial class C { void F() {} }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F"), preserveLocalVariables: false) }), DocumentResults() }); } [Fact] public void PartialMember_DeleteInsert_MultipleDocuments() { var srcA1 = "partial class C { void F() {} }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { void F() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F"), preserveLocalVariables: false) }) }); } [Fact] public void PartialMember_DeleteInsert_GenericMethod() { var srcA1 = "partial class C { void F<T>() {} }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { void F<T>() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.GenericMethodUpdate, "void F<T>()"), Diagnostic(RudeEditKind.GenericMethodUpdate, "T") }) }); } [Fact] public void PartialMember_DeleteInsert_GenericType() { var srcA1 = "partial class C<T> { void F() {} }"; var srcB1 = "partial class C<T> { }"; var srcA2 = "partial class C<T> { }"; var srcB2 = "partial class C<T> { void F() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "void F()") }) }); } [Fact] public void PartialMember_DeleteInsert_Destructor() { var srcA1 = "partial class C { ~C() {} }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { ~C() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("Finalize"), preserveLocalVariables: false), }) }); } [Fact] public void PartialNestedType_InsertDeleteAndChange() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { class D { void M() {} } interface I { } }"; var srcA2 = "partial class C { class D : I { void M() {} } interface I { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class D", FeaturesResources.class_), }), DocumentResults() }); } [Fact, WorkItem(51011, "https://github.com/dotnet/roslyn/issues/51011")] public void PartialMember_RenameInsertDelete() { // The syntactic analysis for A and B produce rename edits since it doesn't see that the member was in fact moved. // TODO: Currently, we don't even pass rename edits to semantic analysis where we could handle them as updates. var srcA1 = "partial class C { void F1() {} }"; var srcB1 = "partial class C { void F2() {} }"; var srcA2 = "partial class C { void F2() {} }"; var srcB2 = "partial class C { void F1() {} }"; // current outcome: GetTopEdits(srcA1, srcA2).VerifyRudeDiagnostics(Diagnostic(RudeEditKind.Renamed, "void F2()", FeaturesResources.method)); GetTopEdits(srcB1, srcB2).VerifyRudeDiagnostics(Diagnostic(RudeEditKind.Renamed, "void F1()", FeaturesResources.method)); // correct outcome: //EditAndContinueValidation.VerifySemantics( // new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, // new[] // { // DocumentResults(semanticEdits: new[] // { // SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F2")), // }), // DocumentResults( // semanticEdits: new[] // { // SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F1")), // }) // }); } [Fact] public void PartialMember_DeleteInsert_UpdateMethodBodyError() { var srcA1 = @" using System.Collections.Generic; partial class C { IEnumerable<int> F() { yield return 1; } } "; var srcB1 = @" using System.Collections.Generic; partial class C { } "; var srcA2 = @" using System.Collections.Generic; partial class C { } "; var srcB2 = @" using System.Collections.Generic; partial class C { IEnumerable<int> F() { yield return 1; yield return 2; } } "; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.Insert, "yield return 2;", CSharpFeaturesResources.yield_return_statement) }) }); } [Fact] public void PartialMember_DeleteInsert_UpdatePropertyAccessors() { var srcA1 = "partial class C { int P { get => 1; set { Console.WriteLine(1); } } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int P { get => 2; set { Console.WriteLine(2); } } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod) }) }); } [Fact] public void PartialMember_DeleteInsert_UpdateAutoProperty() { var srcA1 = "partial class C { int P => 1; }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int P => 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod) }) }); } [Fact] public void PartialMember_DeleteInsert_AddFieldInitializer() { var srcA1 = "partial class C { int f; }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int f = 1; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }) }); } [Fact] public void PartialMember_DeleteInsert_RemoveFieldInitializer() { var srcA1 = "partial class C { int f = 1; }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int f; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }) }); } [Fact] public void PartialMember_DeleteInsert_ConstructorWithInitializers() { var srcA1 = "partial class C { int f = 1; C(int x) { f = x; } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { int f = 1; }"; var srcB2 = "partial class C { C(int x) { f = x + 1; } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }) }); } [Fact] public void PartialMember_DeleteInsert_MethodAddParameter() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { void F() {} }"; var srcA2 = "partial struct S { void F(int x) {} }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("S.F")) }), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial struct S", DeletedSymbolDisplay(FeaturesResources.method, "F()")) }) }); } [Fact] public void PartialMember_DeleteInsert_UpdateMethodParameterType() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { void F(int x); }"; var srcA2 = "partial struct S { void F(byte x); }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("S.F")) }), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial struct S", DeletedSymbolDisplay(FeaturesResources.method, "F(int x)")) }) }); } [Fact] public void PartialMember_DeleteInsert_MethodAddTypeParameter() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { void F(); }"; var srcA2 = "partial struct S { void F<T>(); }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.InsertGenericMethod, "void F<T>()", FeaturesResources.method) }), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial struct S", DeletedSymbolDisplay(FeaturesResources.method, "F()")) }) }); } #endregion #region Methods [Theory] [InlineData("static")] [InlineData("virtual")] [InlineData("abstract")] [InlineData("override")] [InlineData("sealed override", "override")] public void Method_Modifiers_Update(string oldModifiers, string newModifiers = "") { if (oldModifiers != "") { oldModifiers += " "; } if (newModifiers != "") { newModifiers += " "; } var src1 = "class C { " + oldModifiers + "int F() => 0; }"; var src2 = "class C { " + newModifiers + "int F() => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [" + oldModifiers + "int F() => 0;]@10 -> [" + newModifiers + "int F() => 0;]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, newModifiers + "int F()", FeaturesResources.method)); } [Fact] public void Method_NewModifier_Add() { var src1 = "class C { int F() => 0; }"; var src2 = "class C { new int F() => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [int F() => 0;]@10 -> [new int F() => 0;]@10"); // Currently, an edit is produced eventhough there is no metadata/IL change. Consider improving. edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F"))); } [Fact] public void Method_NewModifier_Remove() { var src1 = "class C { new int F() => 0; }"; var src2 = "class C { int F() => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [new int F() => 0;]@10 -> [int F() => 0;]@10"); // Currently, an edit is produced eventhough there is no metadata/IL change. Consider improving. edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F"))); } [Fact] public void Method_ReadOnlyModifier_Add_InMutableStruct() { var src1 = @" struct S { public int M() => 1; }"; var src2 = @" struct S { public readonly int M() => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public readonly int M()", FeaturesResources.method)); } [Fact] public void Method_ReadOnlyModifier_Add_InReadOnlyStruct1() { var src1 = @" readonly struct S { public int M() => 1; }"; var src2 = @" readonly struct S { public readonly int M() => 1; }"; var edits = GetTopEdits(src1, src2); // Currently, an edit is produced eventhough the body nor IsReadOnly attribute have changed. Consider improving. edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember<IMethodSymbol>("M"))); } [Fact] public void Method_ReadOnlyModifier_Add_InReadOnlyStruct2() { var src1 = @" readonly struct S { public int M() => 1; }"; var src2 = @" struct S { public readonly int M() => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "struct S", "struct")); } [Fact] public void Method_AsyncModifier_Remove() { var src1 = @" class Test { public async Task<int> WaitAsync() { return 1; } }"; var src2 = @" class Test { public Task<int> WaitAsync() { return Task.FromResult(1); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingFromAsynchronousToSynchronous, "public Task<int> WaitAsync()", FeaturesResources.method)); } [Fact] public void Method_AsyncModifier_Add() { var src1 = @" class Test { public Task<int> WaitAsync() { return 1; } }"; var src2 = @" class Test { public async Task<int> WaitAsync() { await Task.Delay(1000); return 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); VerifyPreserveLocalVariables(edits, preserveLocalVariables: false); } [Fact] public void Method_AsyncModifier_Add_NotSupported() { var src1 = @" class Test { public Task<int> WaitAsync() { return 1; } }"; var src2 = @" class Test { public async Task<int> WaitAsync() { await Task.Delay(1000); return 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.MakeMethodAsync, "public async Task<int> WaitAsync()")); } [Theory] [InlineData("string", "string?")] [InlineData("object", "dynamic")] [InlineData("(int a, int b)", "(int a, int c)")] public void Method_ReturnType_Update_RuntimeTypeUnchanged(string oldType, string newType) { var src1 = "class C { " + oldType + " M() => default; }"; var src2 = "class C { " + newType + " M() => default; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M"))); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void Method_ReturnType_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C { " + oldType + " M() => default; }"; var src2 = "class C { " + newType + " M() => default; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, newType + " M()", FeaturesResources.method)); } [Fact] public void Method_Update() { var src1 = @" class C { static void Main(string[] args) { int a = 1; int b = 2; System.Console.WriteLine(a + b); } } "; var src2 = @" class C { static void Main(string[] args) { int b = 2; int a = 1; System.Console.WriteLine(a + b); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Update [static void Main(string[] args) { int a = 1; int b = 2; System.Console.WriteLine(a + b); }]@18 -> [static void Main(string[] args) { int b = 2; int a = 1; System.Console.WriteLine(a + b); }]@18"); edits.VerifyRudeDiagnostics(); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Main"), preserveLocalVariables: false) }); } [Fact] public void MethodWithExpressionBody_Update() { var src1 = @" class C { static int Main(string[] args) => F(1); static int F(int a) => 1; } "; var src2 = @" class C { static int Main(string[] args) => F(2); static int F(int a) => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Update [static int Main(string[] args) => F(1);]@18 -> [static int Main(string[] args) => F(2);]@18"); edits.VerifyRudeDiagnostics(); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Main"), preserveLocalVariables: false) }); } [Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")] public void MethodWithExpressionBody_Update_LiftedParameter() { var src1 = @" using System; class C { int M(int a) => new Func<int>(() => a + 1)(); } "; var src2 = @" using System; class C { int M(int a) => new Func<int>(() => 2)(); // not capturing a anymore }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int M(int a) => new Func<int>(() => a + 1)();]@35 -> [int M(int a) => new Func<int>(() => 2)();]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a")); } [Fact] public void MethodWithExpressionBody_ToBlockBody() { var src1 = "class C { static int F(int a) => 1; }"; var src2 = "class C { static int F(int a) { return 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [static int F(int a) => 1;]@10 -> [static int F(int a) { return 2; }]@10"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: false) }); } [Fact] public void MethodWithBlockBody_ToExpressionBody() { var src1 = "class C { static int F(int a) { return 2; } }"; var src2 = "class C { static int F(int a) => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [static int F(int a) { return 2; }]@10 -> [static int F(int a) => 1;]@10"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: false) }); } [Fact] public void MethodWithLambda_Update() { var src1 = @" using System; class C { static void F() { Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; } } "; var src2 = @" using System; class C { static void F() { Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; Console.WriteLine(1); } }"; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), syntaxMap[0]) }); } [Fact] public void MethodUpdate_LocalVariableDeclaration() { var src1 = @" class C { static void Main(string[] args) { int x = 1; Console.WriteLine(x); } } "; var src2 = @" class C { static void Main(string[] args) { int x = 2; Console.WriteLine(x); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Update [static void Main(string[] args) { int x = 1; Console.WriteLine(x); }]@18 -> [static void Main(string[] args) { int x = 2; Console.WriteLine(x); }]@18"); } [Fact] public void Method_Delete() { var src1 = @" class C { void goo() { } } "; var src2 = @" class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [void goo() { }]@18", "Delete [()]@26"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.method, "goo()"))); } [Fact] public void MethodWithExpressionBody_Delete() { var src1 = @" class C { int goo() => 1; } "; var src2 = @" class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [int goo() => 1;]@18", "Delete [()]@25"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.method, "goo()"))); } [WorkItem(754853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754853")] [Fact] public void MethodDelete_WithParameterAndAttribute() { var src1 = @" class C { [Obsolete] void goo(int a) { } } "; var src2 = @" class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Delete [[Obsolete] void goo(int a) { }]@18", "Delete [(int a)]@42", "Delete [int a]@43"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.method, "goo(int a)"))); } [WorkItem(754853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754853")] [Fact] public void MethodDelete_PInvoke() { var src1 = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] public static extern int puts(string c); } "; var src2 = @" using System; using System.Runtime.InteropServices; class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Delete [[DllImport(""msvcrt.dll"")] public static extern int puts(string c);]@74", "Delete [(string c)]@134", "Delete [string c]@135"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.method, "puts(string c)"))); } [Fact] public void MethodInsert_NotSupportedByRuntime() { var src1 = "class C { }"; var src2 = "class C { void goo() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "void goo()", FeaturesResources.method)); } [Fact] public void PrivateMethodInsert() { var src1 = @" class C { static void Main(string[] args) { Console.ReadLine(); } }"; var src2 = @" class C { void goo() { } static void Main(string[] args) { Console.ReadLine(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [void goo() { }]@18", "Insert [()]@26"); edits.VerifyRudeDiagnostics(); } [WorkItem(755784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784")] [Fact] public void PrivateMethodInsert_WithParameters() { var src1 = @" using System; class C { static void Main(string[] args) { Console.ReadLine(); } }"; var src2 = @" using System; class C { void goo(int a) { } static void Main(string[] args) { Console.ReadLine(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [void goo(int a) { }]@35", "Insert [(int a)]@43", "Insert [int a]@44"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.goo")) }); } [WorkItem(755784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784")] [Fact] public void PrivateMethodInsert_WithAttribute() { var src1 = @" class C { static void Main(string[] args) { Console.ReadLine(); } }"; var src2 = @" class C { [System.Obsolete] void goo(int a) { } static void Main(string[] args) { Console.ReadLine(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Insert [[System.Obsolete] void goo(int a) { }]@18", "Insert [(int a)]@49", "Insert [int a]@50"); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodInsert_Virtual() { var src1 = @" class C { }"; var src2 = @" class C { public virtual void F() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertVirtual, "public virtual void F()", FeaturesResources.method)); } [Fact] public void MethodInsert_Abstract() { var src1 = @" abstract class C { }"; var src2 = @" abstract class C { public abstract void F(); } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertVirtual, "public abstract void F()", FeaturesResources.method)); } [Fact] public void MethodInsert_Override() { var src1 = @" class C { }"; var src2 = @" class C { public override void F() { } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertVirtual, "public override void F()", FeaturesResources.method)); } [WorkItem(755784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784"), WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] [Fact] public void ExternMethodInsert() { var src1 = @" using System; using System.Runtime.InteropServices; class C { }"; var src2 = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] private static extern int puts(string c); } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Insert [[DllImport(""msvcrt.dll"")] private static extern int puts(string c);]@74", "Insert [(string c)]@135", "Insert [string c]@136"); // CLR doesn't support methods without a body edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertExtern, "private static extern int puts(string c)", FeaturesResources.method)); } [Fact] [WorkItem(755784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784"), WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] public void ExternMethodDeleteInsert() { var srcA1 = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] private static extern int puts(string c); }"; var srcA2 = @" using System; using System.Runtime.InteropServices; "; var srcB1 = @" using System; using System.Runtime.InteropServices; "; var srcB2 = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] private static extern int puts(string c); } "; // TODO: The method does not need to be updated since there are no sequence points generated for it. EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.puts")), }) }); } [Fact] [WorkItem(755784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784"), WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] public void ExternMethod_Attribute_DeleteInsert() { var srcA1 = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] private static extern int puts(string c); }"; var srcA2 = @" using System; using System.Runtime.InteropServices; "; var srcB1 = @" using System; using System.Runtime.InteropServices; "; var srcB2 = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] [Obsolete] private static extern int puts(string c); } "; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.puts")), }) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void MethodReorder1() { var src1 = "class C { void f(int a, int b) { a = b; } void g() { } }"; var src2 = "class C { void g() { } void f(int a, int b) { a = b; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Reorder [void g() { }]@42 -> @10"); } [Fact] public void MethodInsertDelete1() { var src1 = "class C { class D { } void f(int a, int b) { a = b; } }"; var src2 = "class C { class D { void f(int a, int b) { a = b; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [void f(int a, int b) { a = b; }]@20", "Insert [(int a, int b)]@26", "Insert [int a]@27", "Insert [int b]@34", "Delete [void f(int a, int b) { a = b; }]@22", "Delete [(int a, int b)]@28", "Delete [int a]@29", "Delete [int b]@36"); } [Fact] public void MethodUpdate_AddParameter() { var src1 = @" class C { static void Main() { } }"; var src2 = @" class C { static void Main(string[] args) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [string[] args]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "string[] args", FeaturesResources.parameter)); } [Fact] public void MethodUpdate_UpdateParameter() { var src1 = @" class C { static void Main(string[] args) { } }"; var src2 = @" class C { static void Main(string[] b) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [string[] args]@35 -> [string[] b]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "string[] b", FeaturesResources.parameter)); } [Fact] public void Method_Name_Update() { var src1 = @" class C { static void Main(string[] args) { } }"; var src2 = @" class C { static void EntryPoint(string[] args) { } }"; var edits = GetTopEdits(src1, src2); var expectedEdit = @"Update [static void Main(string[] args) { }]@18 -> [static void EntryPoint(string[] args) { }]@18"; edits.VerifyEdits(expectedEdit); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "static void EntryPoint(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_AsyncMethod0() { var src1 = @" class Test { public async Task<int> WaitAsync() { await Task.Delay(1000); return 1; } }"; var src2 = @" class Test { public async Task<int> WaitAsync() { await Task.Delay(500); return 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); VerifyPreserveLocalVariables(edits, preserveLocalVariables: true); } [Fact] public void MethodUpdate_AsyncMethod1() { var src1 = @" class Test { static void Main(string[] args) { Test f = new Test(); string result = f.WaitAsync().Result; } public async Task<string> WaitAsync() { await Task.Delay(1000); return ""Done""; } }"; var src2 = @" class Test { static void Main(string[] args) { Test f = new Test(); string result = f.WaitAsync().Result; } public async Task<string> WaitAsync() { await Task.Delay(1000); return ""Not Done""; } }"; var edits = GetTopEdits(src1, src2); var expectedEdit = @"Update [public async Task<string> WaitAsync() { await Task.Delay(1000); return ""Done""; }]@151 -> [public async Task<string> WaitAsync() { await Task.Delay(1000); return ""Not Done""; }]@151"; edits.VerifyEdits(expectedEdit); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_AddReturnTypeAttribute() { var src1 = @" using System; class Test { static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [return: Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(@"Update [static void Main(string[] args) { System.Console.Write(5); }]@38 -> [[return: Obsolete] static void Main(string[] args) { System.Console.Write(5); }]@38"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_AddAttribute() { var src1 = @" using System; class Test { static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(@"Update [static void Main(string[] args) { System.Console.Write(5); }]@38 -> [[Obsolete] static void Main(string[] args) { System.Console.Write(5); }]@38"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_AddAttribute_SupportedByRuntime() { var src1 = @" using System; class Test { static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(@"Update [static void Main(string[] args) { System.Console.Write(5); }]@38 -> [[Obsolete] static void Main(string[] args) { System.Console.Write(5); }]@38"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Test.Main")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void MethodUpdate_Attribute_ArrayParameter() { var src1 = @" class AAttribute : System.Attribute { public AAttribute(int[] nums) { } } class C { [A(new int[] { 1, 2, 3})] void M() { } }"; var src2 = @" class AAttribute : System.Attribute { public AAttribute(int[] nums) { } } class C { [A(new int[] { 4, 5, 6})] void M() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void MethodUpdate_Attribute_ArrayParameter_NoChange() { var src1 = @" class AAttribute : System.Attribute { public AAttribute(int[] nums) { } } class C { [A(new int[] { 1, 2, 3})] void M() { var x = 1; } }"; var src2 = @" class AAttribute : System.Attribute { public AAttribute(int[] nums) { } } class C { [A(new int[] { 1, 2, 3})] void M() { var x = 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M")) }); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_AddAttribute2() { var src1 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete, Serializable] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_AddAttribute3() { var src1 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete] [Serializable] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_AddAttribute4() { var src1 = @" using System; class Test { static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete, Serializable] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_UpdateAttribute() { var src1 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete("""")] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [WorkItem(754853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754853")] [Fact] public void MethodUpdate_DeleteAttribute() { var src1 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_DeleteAttribute2() { var src1 = @" using System; class Test { [Obsolete, Serializable] static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_DeleteAttribute3() { var src1 = @" using System; class Test { [Obsolete] [Serializable] static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_ExplicitlyImplemented1() { var src1 = @" class C : I, J { void I.Goo() { Console.WriteLine(2); } void J.Goo() { Console.WriteLine(1); } }"; var src2 = @" class C : I, J { void I.Goo() { Console.WriteLine(1); } void J.Goo() { Console.WriteLine(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void I.Goo() { Console.WriteLine(2); }]@25 -> [void I.Goo() { Console.WriteLine(1); }]@25", "Update [void J.Goo() { Console.WriteLine(1); }]@69 -> [void J.Goo() { Console.WriteLine(2); }]@69"); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_ExplicitlyImplemented2() { var src1 = @" class C : I, J { void I.Goo() { Console.WriteLine(1); } void J.Goo() { Console.WriteLine(2); } }"; var src2 = @" class C : I, J { void Goo() { Console.WriteLine(1); } void J.Goo() { Console.WriteLine(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void I.Goo() { Console.WriteLine(1); }]@25 -> [void Goo() { Console.WriteLine(1); }]@25"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "void Goo()", FeaturesResources.method)); } [WorkItem(754255, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754255")] [Fact] public void MethodUpdate_UpdateStackAlloc() { var src1 = @" class C { static void Main(string[] args) { int i = 10; unsafe { int* px2 = &i; } } }"; var src2 = @" class C { static void Main(string[] args) { int i = 10; unsafe { char* buffer = stackalloc char[16]; int* px2 = &i; } } }"; var expectedEdit = @"Update [static void Main(string[] args) { int i = 10; unsafe { int* px2 = &i; } }]@18 -> [static void Main(string[] args) { int i = 10; unsafe { char* buffer = stackalloc char[16]; int* px2 = &i; } }]@18"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(expectedEdit); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", FeaturesResources.method)); } [Theory] [InlineData("stackalloc int[3]")] [InlineData("stackalloc int[3] { 1, 2, 3 }")] [InlineData("stackalloc int[] { 1, 2, 3 }")] [InlineData("stackalloc[] { 1, 2, 3 }")] public void MethodUpdate_UpdateStackAlloc2(string stackallocDecl) { var src1 = @"unsafe class C { static int F() { var x = " + stackallocDecl + "; return 1; } }"; var src2 = @"unsafe class C { static int F() { var x = " + stackallocDecl + "; return 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", FeaturesResources.method)); } [Fact] public void MethodUpdate_UpdateStackAllocInLambda1() { var src1 = "unsafe class C { void M() { F(1, () => { int* a = stackalloc int[10]; }); } }"; var src2 = "unsafe class C { void M() { F(2, () => { int* a = stackalloc int[10]; }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_UpdateStackAllocInLambda2() { var src1 = "unsafe class C { void M() { F(1, x => { int* a = stackalloc int[10]; }); } }"; var src2 = "unsafe class C { void M() { F(2, x => { int* a = stackalloc int[10]; }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_UpdateStackAllocInAnonymousMethod() { var src1 = "unsafe class C { void M() { F(1, delegate(int x) { int* a = stackalloc int[10]; }); } }"; var src2 = "unsafe class C { void M() { F(2, delegate(int x) { int* a = stackalloc int[10]; }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_UpdateStackAllocInLocalFunction() { var src1 = "class C { void M() { unsafe void f(int x) { int* a = stackalloc int[10]; } f(1); } }"; var src2 = "class C { void M() { unsafe void f(int x) { int* a = stackalloc int[10]; } f(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_SwitchExpressionInLambda1() { var src1 = "class C { void M() { F(1, a => a switch { 0 => 0, _ => 2 }); } }"; var src2 = "class C { void M() { F(2, a => a switch { 0 => 0, _ => 2 }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_SwitchExpressionInLambda2() { var src1 = "class C { void M() { F(1, a => a switch { 0 => 0, _ => 2 }); } }"; var src2 = "class C { void M() { F(2, a => a switch { 0 => 0, _ => 2 }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_SwitchExpressionInAnonymousMethod() { var src1 = "class C { void M() { F(1, delegate(int a) { return a switch { 0 => 0, _ => 2 }; }); } }"; var src2 = "class C { void M() { F(2, delegate(int a) { return a switch { 0 => 0, _ => 2 }; }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_SwitchExpressionInLocalFunction() { var src1 = "class C { void M() { int f(int a) => a switch { 0 => 0, _ => 2 }; f(1); } }"; var src2 = "class C { void M() { int f(int a) => a switch { 0 => 0, _ => 2 }; f(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_SwitchExpressionInQuery() { var src1 = "class C { void M() { var x = from z in new[] { 1, 2, 3 } where z switch { 0 => true, _ => false } select z + 1; } }"; var src2 = "class C { void M() { var x = from z in new[] { 1, 2, 3 } where z switch { 0 => true, _ => false } select z + 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_UpdateAnonymousMethod() { var src1 = "class C { void M() { F(1, delegate(int a) { return a; }); } }"; var src2 = "class C { void M() { F(2, delegate(int a) { return a; }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodWithExpressionBody_Update_UpdateAnonymousMethod() { var src1 = "class C { void M() => F(1, delegate(int a) { return a; }); }"; var src2 = "class C { void M() => F(2, delegate(int a) { return a; }); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_Query() { var src1 = "class C { void M() { F(1, from goo in bar select baz); } }"; var src2 = "class C { void M() { F(2, from goo in bar select baz); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodWithExpressionBody_Update_Query() { var src1 = "class C { void M() => F(1, from goo in bar select baz); }"; var src2 = "class C { void M() => F(2, from goo in bar select baz); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_AnonymousType() { var src1 = "class C { void M() { F(1, new { A = 1, B = 2 }); } }"; var src2 = "class C { void M() { F(2, new { A = 1, B = 2 }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodWithExpressionBody_Update_AnonymousType() { var src1 = "class C { void M() => F(new { A = 1, B = 2 }); }"; var src2 = "class C { void M() => F(new { A = 10, B = 20 }); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_Iterator_YieldReturn() { var src1 = "class C { IEnumerable<int> M() { yield return 1; } }"; var src2 = "class C { IEnumerable<int> M() { yield return 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); VerifyPreserveLocalVariables(edits, preserveLocalVariables: true); } [Fact] public void MethodUpdate_AddYieldReturn() { var src1 = "class C { IEnumerable<int> M() { return new[] { 1, 2, 3}; } }"; var src2 = "class C { IEnumerable<int> M() { yield return 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); VerifyPreserveLocalVariables(edits, preserveLocalVariables: false); } [Fact] public void MethodUpdate_AddYieldReturn_NotSupported() { var src1 = "class C { IEnumerable<int> M() { return new[] { 1, 2, 3}; } }"; var src2 = "class C { IEnumerable<int> M() { yield return 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.MakeMethodIterator, "IEnumerable<int> M()")); } [Fact] public void MethodUpdate_Iterator_YieldBreak() { var src1 = "class C { IEnumerable<int> M() { F(); yield break; } }"; var src2 = "class C { IEnumerable<int> M() { G(); yield break; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); VerifyPreserveLocalVariables(edits, preserveLocalVariables: true); } [WorkItem(1087305, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087305")] [Fact] public void MethodUpdate_LabeledStatement() { var src1 = @" class C { static void Main(string[] args) { goto Label1; Label1: { Console.WriteLine(1); } } }"; var src2 = @" class C { static void Main(string[] args) { goto Label1; Label1: { Console.WriteLine(2); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_LocalFunctionsParameterRefnessInBody() { var src1 = @"class C { public void M(int a) { void f(ref int b) => b = 1; } }"; var src2 = @"class C { public void M(int a) { void f(out int b) => b = 1; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public void M(int a) { void f(ref int b) => b = 1; }]@10 -> [public void M(int a) { void f(out int b) => b = 1; }]@10"); } [Fact] public void MethodUpdate_LambdaParameterRefnessInBody() { var src1 = @"class C { public void M(int a) { f((ref int b) => b = 1); } }"; var src2 = @"class C { public void M(int a) { f((out int b) => b = 1); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public void M(int a) { f((ref int b) => b = 1); }]@10 -> [public void M(int a) { f((out int b) => b = 1); }]@10"); } [Fact] public void Method_ReadOnlyRef_Parameter_InsertWhole() { var src1 = "class Test { }"; var src2 = "class Test { int M(in int b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [int M(in int b) => throw null;]@13", "Insert [(in int b)]@18", "Insert [in int b]@19"); edits.VerifyRudeDiagnostics(); } [Fact] public void Method_ReadOnlyRef_Parameter_InsertParameter() { var src1 = "class Test { int M() => throw null; }"; var src2 = "class Test { int M(in int b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [in int b]@19"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "in int b", FeaturesResources.parameter)); } [Fact] public void Method_ReadOnlyRef_Parameter_Update() { var src1 = "class Test { int M(int b) => throw null; }"; var src2 = "class Test { int M(in int b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int b]@19 -> [in int b]@19"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "in int b", FeaturesResources.parameter)); } [Fact] public void Method_ReadOnlyRef_ReturnType_Insert() { var src1 = "class Test { }"; var src2 = "class Test { ref readonly int M() => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [ref readonly int M() => throw null;]@13", "Insert [()]@31"); edits.VerifyRudeDiagnostics(); } [Fact] public void Method_ReadOnlyRef_ReturnType_Update() { var src1 = "class Test { int M() => throw null; }"; var src2 = "class Test { ref readonly int M() => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int M() => throw null;]@13 -> [ref readonly int M() => throw null;]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "ref readonly int M()", FeaturesResources.method)); } [Fact] public void Method_ImplementingInterface_Add() { var src1 = @" using System; public interface ISample { string Get(); } public interface IConflict { string Get(); } public class BaseClass : ISample { public virtual string Get() => string.Empty; } public class SubClass : BaseClass, IConflict { public override string Get() => string.Empty; } "; var src2 = @" using System; public interface ISample { string Get(); } public interface IConflict { string Get(); } public class BaseClass : ISample { public virtual string Get() => string.Empty; } public class SubClass : BaseClass, IConflict { public override string Get() => string.Empty; string IConflict.Get() => String.Empty; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [string IConflict.Get() => String.Empty;]@325", "Insert [()]@345"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertMethodWithExplicitInterfaceSpecifier, "string IConflict.Get()", FeaturesResources.method)); } [Fact] public void Method_Partial_DeleteInsert_DefinitionPart() { var srcA1 = "partial class C { partial void F(); }"; var srcB1 = "partial class C { partial void F() { } }"; var srcC1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { partial void F() { } }"; var srcC2 = "partial class C { partial void F(); }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults(), DocumentResults(), }); } [Fact] public void Method_Partial_DeleteInsert_ImplementationPart() { var srcA1 = "partial class C { partial void F(); }"; var srcB1 = "partial class C { partial void F() { } }"; var srcC1 = "partial class C { }"; var srcA2 = "partial class C { partial void F(); }"; var srcB2 = "partial class C { }"; var srcC2 = "partial class C { partial void F() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F").PartialImplementationPart) }), }); } [Fact, WorkItem(51011, "https://github.com/dotnet/roslyn/issues/51011")] public void Method_Partial_Swap_ImplementationAndDefinitionParts() { var srcA1 = "partial class C { partial void F(); }"; var srcB1 = "partial class C { partial void F() { } }"; var srcA2 = "partial class C { partial void F() { } }"; var srcB2 = "partial class C { partial void F(); }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F").PartialImplementationPart) }), DocumentResults(), }); } [Fact] public void Method_Partial_DeleteImplementation() { var srcA1 = "partial class C { partial void F(); }"; var srcB1 = "partial class C { partial void F() { } }"; var srcA2 = "partial class C { partial void F(); }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial class C", DeletedSymbolDisplay(FeaturesResources.method, "F()")) }) }); } [Fact] public void Method_Partial_DeleteBoth() { var srcA1 = "partial class C { partial void F(); }"; var srcB1 = "partial class C { partial void F() { } }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial class C", DeletedSymbolDisplay(FeaturesResources.method, "F()")) }) }); } [Fact] public void Method_Partial_DeleteInsertBoth() { var srcA1 = "partial class C { partial void F(); }"; var srcB1 = "partial class C { partial void F() { } }"; var srcC1 = "partial class C { }"; var srcD1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { }"; var srcC2 = "partial class C { partial void F(); }"; var srcD2 = "partial class C { partial void F() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2), GetTopEdits(srcD1, srcD2) }, new[] { DocumentResults(), DocumentResults(), DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F").PartialImplementationPart) }) }); } [Fact] public void Method_Partial_Insert() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { partial void F(); }"; var srcB2 = "partial class C { partial void F() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F").PartialImplementationPart) }), }); } [Fact] public void Method_Partial_Insert_Reloadable() { var srcA1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { }"; var srcB1 = "partial class C { }"; var srcA2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { partial void F(); }"; var srcB2 = "partial class C { partial void F() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C") }), }); } #endregion #region Operators [Theory] [InlineData("implicit", "explicit")] [InlineData("explicit", "implicit")] public void Operator_Modifiers_Update(string oldModifiers, string newModifiers) { var src1 = "class C { public static " + oldModifiers + " operator int (C c) => 0; }"; var src2 = "class C { public static " + newModifiers + " operator int (C c) => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [public static " + oldModifiers + " operator int (C c) => 0;]@10 -> [public static " + newModifiers + " operator int (C c) => 0;]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public static " + newModifiers + " operator int (C c)", CSharpFeaturesResources.conversion_operator)); } [Fact] public void Operator_Modifiers_Update_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { public static implicit operator int (C c) => 0; }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { public static explicit operator int (C c) => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Operator_Conversion_ExternModifiers_Add() { var src1 = "class C { public static implicit operator bool (C c) => default; }"; var src2 = "class C { extern public static implicit operator bool (C c); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "extern public static implicit operator bool (C c)", CSharpFeaturesResources.conversion_operator)); } [Fact] public void Operator_Conversion_ExternModifiers_Remove() { var src1 = "class C { extern public static implicit operator bool (C c); }"; var src2 = "class C { public static implicit operator bool (C c) => default; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public static implicit operator bool (C c)", CSharpFeaturesResources.conversion_operator)); } [Fact] public void OperatorInsert() { var src1 = @" class C { } "; var src2 = @" class C { public static implicit operator bool (C c) { return false; } public static C operator +(C c, C d) { return c; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertOperator, "public static implicit operator bool (C c)", CSharpFeaturesResources.conversion_operator), Diagnostic(RudeEditKind.InsertOperator, "public static C operator +(C c, C d)", FeaturesResources.operator_)); } [Fact] public void OperatorDelete() { var src1 = @" class C { public static implicit operator bool (C c) { return false; } public static C operator +(C c, C d) { return c; } } "; var src2 = @" class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(CSharpFeaturesResources.conversion_operator, "implicit operator bool(C c)")), Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.operator_, "operator +(C c, C d)"))); } [Fact] public void OperatorInsertDelete() { var srcA1 = @" partial class C { public static implicit operator bool (C c) => false; } "; var srcB1 = @" partial class C { public static C operator +(C c, C d) => c; } "; var srcA2 = srcB1; var srcB2 = srcA1; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("op_Addition")) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("op_Implicit")) }), }); } [Fact] public void OperatorUpdate() { var src1 = @" class C { public static implicit operator bool (C c) { return false; } public static C operator +(C c, C d) { return c; } } "; var src2 = @" class C { public static implicit operator bool (C c) { return true; } public static C operator +(C c, C d) { return d; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Implicit")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Addition")), }); } [Fact] public void OperatorWithExpressionBody_Update() { var src1 = @" class C { public static implicit operator bool (C c) => false; public static C operator +(C c, C d) => c; } "; var src2 = @" class C { public static implicit operator bool (C c) => true; public static C operator +(C c, C d) => d; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Implicit")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Addition")), }); } [Fact] public void OperatorWithExpressionBody_ToBlockBody() { var src1 = "class C { public static C operator +(C c, C d) => d; }"; var src2 = "class C { public static C operator +(C c, C d) { return c; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [public static C operator +(C c, C d) => d;]@10 -> [public static C operator +(C c, C d) { return c; }]@10"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Addition")) }); } [Fact] public void OperatorWithBlockBody_ToExpressionBody() { var src1 = "class C { public static C operator +(C c, C d) { return c; } }"; var src2 = "class C { public static C operator +(C c, C d) => d; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [public static C operator +(C c, C d) { return c; }]@10 -> [public static C operator +(C c, C d) => d;]@10"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Addition")) }); } [Fact] public void OperatorReorder1() { var src1 = @" class C { public static implicit operator bool (C c) { return false; } public static implicit operator int (C c) { return 1; } } "; var src2 = @" class C { public static implicit operator int (C c) { return 1; } public static implicit operator bool (C c) { return false; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [public static implicit operator int (C c) { return 1; }]@84 -> @18"); edits.VerifyRudeDiagnostics(); } [Fact] public void OperatorReorder2() { var src1 = @" class C { public static C operator +(C c, C d) { return c; } public static C operator -(C c, C d) { return d; } } "; var src2 = @" class C { public static C operator -(C c, C d) { return d; } public static C operator +(C c, C d) { return c; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [public static C operator -(C c, C d) { return d; }]@74 -> @18"); edits.VerifyRudeDiagnostics(); } [Fact] public void Operator_ReadOnlyRef_Parameter_InsertWhole() { var src1 = "class Test { }"; var src2 = "class Test { public static bool operator !(in Test b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [public static bool operator !(in Test b) => throw null;]@13", "Insert [(in Test b)]@42", "Insert [in Test b]@43"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertOperator, "public static bool operator !(in Test b)", FeaturesResources.operator_)); } [Fact] public void Operator_ReadOnlyRef_Parameter_Update() { var src1 = "class Test { public static bool operator !(Test b) => throw null; }"; var src2 = "class Test { public static bool operator !(in Test b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Test b]@43 -> [in Test b]@43"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "in Test b", FeaturesResources.parameter)); } #endregion #region Constructor, Destructor [Fact] public void Constructor_Parameter_AddAttribute() { var src1 = @" class C { private int x = 1; public C(int a) { } }"; var src2 = @" class C { private int x = 2; public C([System.Obsolete]int a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [x = 1]@30 -> [x = 2]@30", "Update [int a]@53 -> [[System.Obsolete]int a]@53"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C..ctor")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] [WorkItem(2068, "https://github.com/dotnet/roslyn/issues/2068")] public void Constructor_ExternModifier_Add() { var src1 = "class C { }"; var src2 = "class C { public extern C(); }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [public extern C();]@10", "Insert [()]@25"); // This can be allowed as the compiler generates an empty constructor, but it's not worth the complexity. edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public extern C()", FeaturesResources.constructor)); } [Fact] public void ConstructorInitializer_Update1() { var src1 = @" class C { public C(int a) : base(a) { } }"; var src2 = @" class C { public C(int a) : base(a + 1) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public C(int a) : base(a) { }]@18 -> [public C(int a) : base(a + 1) { }]@18"); edits.VerifyRudeDiagnostics(); } [Fact] public void ConstructorInitializer_Update2() { var src1 = @" class C<T> { public C(int a) : base(a) { } }"; var src2 = @" class C<T> { public C(int a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public C(int a) : base(a) { }]@21 -> [public C(int a) { }]@21"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.GenericTypeUpdate, "public C(int a)")); } [Fact] public void ConstructorInitializer_Update3() { var src1 = @" class C { public C(int a) { } }"; var src2 = @" class C { public C(int a) : base(a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public C(int a) { }]@18 -> [public C(int a) : base(a) { }]@18"); edits.VerifyRudeDiagnostics(); } [Fact] public void ConstructorInitializer_Update4() { var src1 = @" class C<T> { public C(int a) : base(a) { } }"; var src2 = @" class C<T> { public C(int a) : base(a + 1) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public C(int a) : base(a) { }]@21 -> [public C(int a) : base(a + 1) { }]@21"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.GenericTypeUpdate, "public C(int a)")); } [WorkItem(743552, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/743552")] [Fact] public void ConstructorUpdate_AddParameter() { var src1 = @" class C { public C(int a) { } }"; var src2 = @" class C { public C(int a, int b) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int a)]@26 -> [(int a, int b)]@26", "Insert [int b]@34"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "int b", FeaturesResources.parameter)); } [Fact] public void DestructorDelete() { var src1 = @"class B { ~B() { } }"; var src2 = @"class B { }"; var expectedEdit1 = @"Delete [~B() { }]@10"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(expectedEdit1); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class B", DeletedSymbolDisplay(CSharpFeaturesResources.destructor, "~B()"))); } [Fact] public void DestructorDelete_InsertConstructor() { var src1 = @"class B { ~B() { } }"; var src2 = @"class B { B() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [B() { }]@10", "Insert [()]@11", "Delete [~B() { }]@10"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "B()", FeaturesResources.constructor), Diagnostic(RudeEditKind.Delete, "class B", DeletedSymbolDisplay(CSharpFeaturesResources.destructor, "~B()"))); } [Fact] [WorkItem(789577, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/789577")] public void ConstructorUpdate_AnonymousTypeInFieldInitializer() { var src1 = "class C { int a = F(new { A = 1, B = 2 }); C() { x = 1; } }"; var src2 = "class C { int a = F(new { A = 1, B = 2 }); C() { x = 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Constructor_Static_Delete() { var src1 = "class C { static C() { } }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.static_constructor, "C()"))); } [Fact] public void Constructor_Static_Delete_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { static C() { } }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Constructor_Static_Insert() { var src1 = "class C { }"; var src2 = "class C { static C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single()) }); } [Fact] public void InstanceCtorDelete_Public() { var src1 = "class C { public C() { } }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Theory] [InlineData("")] [InlineData("private")] [InlineData("protected")] [InlineData("internal")] [InlineData("private protected")] [InlineData("protected internal")] public void InstanceCtorDelete_NonPublic(string accessibility) { var src1 = "class C { [System.Obsolete] " + accessibility + " C() { } }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()")), Diagnostic(RudeEditKind.ChangingAccessibility, "class C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()"))); } [Fact] public void InstanceCtorDelete_Public_PartialWithInitializerUpdate() { var srcA1 = "partial class C { public C() { } }"; var srcB1 = "partial class C { int x = 1; }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int x = 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }) }); } [Fact] public void InstanceCtorInsert_Public_Implicit() { var src1 = "class C { }"; var src2 = "class C { public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void InstanceCtorInsert_Partial_Public_Implicit() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { public C() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // no change in document A DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void InstanceCtorInsert_Public_NoImplicit() { var src1 = "class C { public C(int a) { } }"; var src2 = "class C { public C(int a) { } public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, expectedSemanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(c => c.Parameters.IsEmpty)) }); } [Fact] public void InstanceCtorInsert_Partial_Public_NoImplicit() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { public C(int a) { } }"; var srcA2 = "partial class C { public C() { } }"; var srcB2 = "partial class C { public C(int a) { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(c => c.Parameters.IsEmpty)) }), // no change in document B DocumentResults(), }); } [Fact] public void InstanceCtorInsert_Private_Implicit1() { var src1 = "class C { }"; var src2 = "class C { private C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "private C()", FeaturesResources.constructor)); } [Fact] public void InstanceCtorInsert_Private_Implicit2() { var src1 = "class C { }"; var src2 = "class C { C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "C()", FeaturesResources.constructor)); } [Fact] public void InstanceCtorInsert_Protected_PublicImplicit() { var src1 = "class C { }"; var src2 = "class C { protected C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "protected C()", FeaturesResources.constructor)); } [Fact] public void InstanceCtorInsert_Internal_PublicImplicit() { var src1 = "class C { }"; var src2 = "class C { internal C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "internal C()", FeaturesResources.constructor)); } [Fact] public void InstanceCtorInsert_Internal_ProtectedImplicit() { var src1 = "abstract class C { }"; var src2 = "abstract class C { internal C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "internal C()", FeaturesResources.constructor)); } [Fact] public void InstanceCtorUpdate_ProtectedImplicit() { var src1 = "abstract class C { }"; var src2 = "abstract class C { protected C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void InstanceCtorInsert_Private_NoImplicit() { var src1 = "class C { public C(int a) { } }"; var src2 = "class C { public C(int a) { } private C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C") .InstanceConstructors.Single(ctor => ctor.DeclaredAccessibility == Accessibility.Private)) }); } [Fact] public void InstanceCtorInsert_Internal_NoImplicit() { var src1 = "class C { public C(int a) { } }"; var src2 = "class C { public C(int a) { } internal C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void InstanceCtorInsert_Protected_NoImplicit() { var src1 = "class C { public C(int a) { } }"; var src2 = "class C { public C(int a) { } protected C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void InstanceCtorInsert_InternalProtected_NoImplicit() { var src1 = "class C { public C(int a) { } }"; var src2 = "class C { public C(int a) { } internal protected C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void StaticCtor_Partial_DeleteInsert() { var srcA1 = "partial class C { static C() { } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { static C() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void InstanceCtor_Partial_DeletePrivateInsertPrivate() { var srcA1 = "partial class C { C() { } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { C() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void InstanceCtor_Partial_DeletePublicInsertPublic() { var srcA1 = "partial class C { public C() { } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { public C() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void InstanceCtor_Partial_DeletePrivateInsertPublic() { var srcA1 = "partial class C { C() { } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { public C() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // delete of the constructor in partial part will be reported as rude edit in the other document where it was inserted back with changed accessibility DocumentResults( semanticEdits: NoSemanticEdits), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.ChangingAccessibility, "public C()", FeaturesResources.constructor) }), }); } [Fact] public void StaticCtor_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { static C() { } }"; var srcA2 = "partial class C { static C() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_InsertPublicDeletePublic() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { public C() { } }"; var srcA2 = "partial class C { public C() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_InsertPrivateDeletePrivate() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { private C() { } }"; var srcA2 = "partial class C { private C() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_DeleteInternalInsertInternal() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { internal C() { } }"; var srcA2 = "partial class C { internal C() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_InsertInternalDeleteInternal_WithBody() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { internal C() { } }"; var srcA2 = "partial class C { internal C() { Console.WriteLine(1); } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_InsertPublicDeletePrivate() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { private C() { } }"; var srcA2 = "partial class C { public C() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.ChangingAccessibility, "public C()", FeaturesResources.constructor) }), // delete of the constructor in partial part will be reported as rude in the the other document where it was inserted with changed accessibility DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_InsertInternalDeletePrivate() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { private C() { } }"; var srcA2 = "partial class C { internal C() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.ChangingAccessibility, "internal C()", FeaturesResources.constructor) }), DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_Update_LambdaInInitializer1() { var src1 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); public C() { F(<N:0.2>c => c + 1</N:0.2>); } } "; var src2 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); public C() { F(<N:0.2>c => c + 2</N:0.2>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void InstanceCtor_Partial_Update_LambdaInInitializer_Trivia1() { var src1 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); public C() { F(<N:0.2>c => c + 1</N:0.2>); } } "; var src2 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); /*new trivia*/public C() { F(<N:0.2>c => c + 1</N:0.2>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void InstanceCtor_Partial_Update_LambdaInInitializer_ExplicitInterfaceImpl1() { var src1 = @" using System; public interface I { int B { get; } } public interface J { int B { get; } } partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C : I, J { int I.B { get; } = F(<N:0.1>ib => ib + 1</N:0.1>); int J.B { get; } = F(<N:0.2>jb => jb + 1</N:0.2>); public C() { F(<N:0.3>c => c + 1</N:0.3>); } } "; var src2 = @" using System; public interface I { int B { get; } } public interface J { int B { get; } } partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C : I, J { int I.B { get; } = F(<N:0.1>ib => ib + 1</N:0.1>); int J.B { get; } = F(<N:0.2>jb => jb + 1</N:0.2>); public C() { F(<N:0.3>c => c + 2</N:0.3>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact, WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")] public void InstanceCtor_Partial_Insert_Parameterless_LambdaInInitializer1() { var src1 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); } "; var src2 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); public C() // new ctor { F(c => c + 1); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, "public C()")); // TODO: //var syntaxMap = GetSyntaxMap(src1, src2); //edits.VerifySemantics( // ActiveStatementsDescription.Empty, // new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact, WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")] public void InstanceCtor_Partial_Insert_WithParameters_LambdaInInitializer1() { var src1 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); } "; var src2 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); public C(int x) // new ctor { F(c => c + 1); } } "; var edits = GetTopEdits(src1, src2); _ = GetSyntaxMap(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, "public C(int x)")); // TODO: bug https://github.com/dotnet/roslyn/issues/2504 //edits.VerifySemantics( // ActiveStatementsDescription.Empty, // new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<NamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void InstanceCtor_Partial_Explicit_Update() { var srcA1 = @" using System; partial class C { C(int arg) => Console.WriteLine(0); C(bool arg) => Console.WriteLine(1); } "; var srcB1 = @" using System; partial class C { int a <N:0.0>= 1</N:0.0>; C(uint arg) => Console.WriteLine(2); } "; var srcA2 = @" using System; partial class C { C(int arg) => Console.WriteLine(0); C(bool arg) => Console.WriteLine(1); } "; var srcB2 = @" using System; partial class C { int a <N:0.0>= 2</N:0.0>; // updated field initializer C(uint arg) => Console.WriteLine(2); C(byte arg) => Console.WriteLine(3); // new ctor } "; var syntaxMapB = GetSyntaxMap(srcB1, srcB2)[0]; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // No changes in document A DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Single().Type.Name == "Int32"), partialType: "C", syntaxMap: syntaxMapB), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Single().Type.Name == "Boolean"), partialType: "C", syntaxMap: syntaxMapB), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Single().Type.Name == "UInt32"), partialType: "C", syntaxMap: syntaxMapB), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Single().Type.Name == "Byte"), syntaxMap: null), }) }); } [Fact] public void InstanceCtor_Partial_Explicit_Update_SemanticError() { var srcA1 = @" using System; partial class C { C(int arg) => Console.WriteLine(0); C(int arg) => Console.WriteLine(1); } "; var srcB1 = @" using System; partial class C { int a = 1; } "; var srcA2 = @" using System; partial class C { C(int arg) => Console.WriteLine(0); C(int arg) => Console.WriteLine(1); } "; var srcB2 = @" using System; partial class C { int a = 2; C(int arg) => Console.WriteLine(2); } "; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // No changes in document A DocumentResults(), // The actual edits do not matter since there are semantic errors in the compilation. // We just should not crash. DocumentResults(diagnostics: Array.Empty<RudeEditDiagnosticDescription>()) }); } [Fact] public void InstanceCtor_Partial_Implicit_Update() { var srcA1 = "partial class C { int F = 1; }"; var srcB1 = "partial class C { int G = 1; }"; var srcA2 = "partial class C { int F = 2; }"; var srcB2 = "partial class C { int G = 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void ParameterlessConstructor_SemanticError_Delete1() { var src1 = @" class C { D() {} } "; var src2 = @" class C { } "; var edits = GetTopEdits(src1, src2); // The compiler interprets D() as a constructor declaration. edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "class C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()"))); } [Fact] public void Constructor_SemanticError_Partial() { var src1 = @" partial class C { partial void C(int x); } partial class C { partial void C(int x) { System.Console.WriteLine(1); } } "; var src2 = @" partial class C { partial void C(int x); } partial class C { partial void C(int x) { System.Console.WriteLine(2); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(ActiveStatementsDescription.Empty, expectedSemanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("C").PartialImplementationPart) }); } [Fact] public void PartialDeclaration_Delete() { var srcA1 = "partial class C { public C() { } void F() { } }"; var srcB1 = "partial class C { int x = 1; }"; var srcA2 = ""; var srcB2 = "partial class C { int x = 2; void F() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void PartialDeclaration_Insert() { var srcA1 = ""; var srcB1 = "partial class C { int x = 1; void F() { } }"; var srcA2 = "partial class C { public C() { } void F() { } }"; var srcB2 = "partial class C { int x = 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void PartialDeclaration_Insert_Reloadable() { var srcA1 = ""; var srcB1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { int x = 1; void F() { } }"; var srcA2 = "partial class C { public C() { } void F() { } }"; var srcB2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { int x = 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C") }), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C") }), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Constructor_BlockBodyToExpressionBody() { var src1 = @" public class C { private int _value; public C(int value) { _value = value; } } "; var src2 = @" public class C { private int _value; public C(int value) => _value = value; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [public C(int value) { _value = value; }]@52 -> [public C(int value) => _value = value;]@52"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void ConstructorWithInitializer_BlockBodyToExpressionBody() { var src1 = @" public class B { B(int value) {} } public class C : B { private int _value; public C(int value) : base(value) { _value = value; } } "; var src2 = @" public class B { B(int value) {} } public class C : B { private int _value; public C(int value) : base(value) => _value = value; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [public C(int value) : base(value) { _value = value; }]@90 -> [public C(int value) : base(value) => _value = value;]@90"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Constructor_ExpressionBodyToBlockBody() { var src1 = @" public class C { private int _value; public C(int value) => _value = value; } "; var src2 = @" public class C { private int _value; public C(int value) { _value = value; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(@"Update [public C(int value) => _value = value;]@52 -> [public C(int value) { _value = value; }]@52"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void ConstructorWithInitializer_ExpressionBodyToBlockBody() { var src1 = @" public class B { B(int value) {} } public class C : B { private int _value; public C(int value) : base(value) => _value = value; } "; var src2 = @" public class B { B(int value) {} } public class C : B { private int _value; public C(int value) : base(value) { _value = value; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(@"Update [public C(int value) : base(value) => _value = value;]@90 -> [public C(int value) : base(value) { _value = value; }]@90"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Destructor_BlockBodyToExpressionBody() { var src1 = @" public class C { ~C() { Console.WriteLine(0); } } "; var src2 = @" public class C { ~C() => Console.WriteLine(0); } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [~C() { Console.WriteLine(0); }]@25 -> [~C() => Console.WriteLine(0);]@25"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Finalize"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Destructor_ExpressionBodyToBlockBody() { var src1 = @" public class C { ~C() => Console.WriteLine(0); } "; var src2 = @" public class C { ~C() { Console.WriteLine(0); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [~C() => Console.WriteLine(0);]@25 -> [~C() { Console.WriteLine(0); }]@25"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Finalize"), preserveLocalVariables: false) }); } [Fact] public void Constructor_ReadOnlyRef_Parameter_InsertWhole() { var src1 = "class Test { }"; var src2 = "class Test { Test(in int b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [Test(in int b) => throw null;]@13", "Insert [(in int b)]@17", "Insert [in int b]@18"); edits.VerifyRudeDiagnostics(); } [Fact] public void Constructor_ReadOnlyRef_Parameter_InsertParameter() { var src1 = "class Test { Test() => throw null; }"; var src2 = "class Test { Test(in int b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [in int b]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "in int b", FeaturesResources.parameter)); } [Fact] public void Constructor_ReadOnlyRef_Parameter_Update() { var src1 = "class Test { Test(int b) => throw null; }"; var src2 = "class Test { Test(in int b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int b]@18 -> [in int b]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "in int b", FeaturesResources.parameter)); } #endregion #region Fields and Properties with Initializers [Fact] public void FieldInitializer_Update1() { var src1 = "class C { int a = 0; }"; var src2 = "class C { int a = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 0]@14 -> [a = 1]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializer_Update1() { var src1 = "class C { int a { get; } = 0; }"; var src2 = "class C { int a { get; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a { get; } = 0;]@10 -> [int a { get; } = 1;]@10"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializer_Update2() { var src1 = "class C { int a = 0; }"; var src2 = "class C { int a; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 0]@14 -> [a]@14"); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyInitializer_Update2() { var src1 = "class C { int a { get; } = 0; }"; var src2 = "class C { int a { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a { get; } = 0;]@10 -> [int a { get { return 1; } }]@10", "Update [get;]@18 -> [get { return 1; }]@18"); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.a").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), preserveLocalVariables: true)); } [Fact] public void PropertyInitializer_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int a { get; } = 0; }"; var srcA2 = "partial class C { int a { get { return 1; } } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.a").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults() }); } [Fact] public void FieldInitializer_Update3() { var src1 = "class C { int a; }"; var src2 = "class C { int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@14 -> [a = 0]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializer_Update3() { var src1 = "class C { int a { get { return 1; } } }"; var src2 = "class C { int a { get; } = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a { get { return 1; } }]@10 -> [int a { get; } = 0;]@10", "Update [get { return 1; }]@18 -> [get;]@18"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.a").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_StaticCtorUpdate1() { var src1 = "class C { static int a; static C() { } }"; var src2 = "class C { static int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@21 -> [a = 0]@21", "Delete [static C() { }]@24", "Delete [()]@32"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_StaticCtorUpdate1() { var src1 = "class C { static int a { get; } = 1; static C() { } }"; var src2 = "class C { static int a { get; } = 2;}"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_InstanceCtorUpdate_Private() { var src1 = "class C { int a; [System.Obsolete]C() { } }"; var src2 = "class C { int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()")), Diagnostic(RudeEditKind.ChangingAccessibility, "class C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()"))); } [Fact] public void PropertyInitializerUpdate_InstanceCtorUpdate_Private() { var src1 = "class C { int a { get; } = 1; C() { } }"; var src2 = "class C { int a { get; } = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "class C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()"))); } [Fact] public void FieldInitializerUpdate_InstanceCtorUpdate_Public() { var src1 = "class C { int a; public C() { } }"; var src2 = "class C { int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_InstanceCtorUpdate_Public() { var src1 = "class C { int a { get; } = 1; public C() { } }"; var src2 = "class C { int a { get; } = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_StaticCtorUpdate2() { var src1 = "class C { static int a; static C() { } }"; var src2 = "class C { static int a = 0; static C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@21 -> [a = 0]@21"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_StaticCtorUpdate2() { var src1 = "class C { static int a { get; } = 1; static C() { } }"; var src2 = "class C { static int a { get; } = 2; static C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_InstanceCtorUpdate2() { var src1 = "class C { int a; public C() { } }"; var src2 = "class C { int a = 0; public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@14 -> [a = 0]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_InstanceCtorUpdate2() { var src1 = "class C { int a { get; } = 1; public C() { } }"; var src2 = "class C { int a { get; } = 2; public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_InstanceCtorUpdate3() { var src1 = "class C { int a; }"; var src2 = "class C { int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@14 -> [a = 0]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_InstanceCtorUpdate3() { var src1 = "class C { int a { get; } = 1; }"; var src2 = "class C { int a { get; } = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_InstanceCtorUpdate4() { var src1 = "class C { int a = 0; }"; var src2 = "class C { int a; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 0]@14 -> [a]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_InstanceCtorUpdate5() { var src1 = "class C { int a; private C(int a) { } private C(bool a) { } }"; var src2 = "class C { int a = 0; private C(int a) { } private C(bool a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@14 -> [a = 0]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(int)"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(bool)"), preserveLocalVariables: true), }); } [Fact] public void PropertyInitializerUpdate_InstanceCtorUpdate5() { var src1 = "class C { int a { get; } = 1; private C(int a) { } private C(bool a) { } }"; var src2 = "class C { int a { get; } = 10000; private C(int a) { } private C(bool a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(int)"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(bool)"), preserveLocalVariables: true), }); } [Fact] public void FieldInitializerUpdate_InstanceCtorUpdate6() { var src1 = "class C { int a; private C(int a) : this(true) { } private C(bool a) { } }"; var src2 = "class C { int a = 0; private C(int a) : this(true) { } private C(bool a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@14 -> [a = 0]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(bool)"), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_StaticCtorInsertImplicit() { var src1 = "class C { static int a; }"; var src2 = "class C { static int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@21 -> [a = 0]@21"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single()) }); } [Fact] public void FieldInitializerUpdate_StaticCtorInsertExplicit() { var src1 = "class C { static int a; }"; var src2 = "class C { static int a = 0; static C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [static C() { }]@28", "Insert [()]@36", "Update [a]@21 -> [a = 0]@21"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single()) }); } [Fact] public void FieldInitializerUpdate_InstanceCtorInsertExplicit() { var src1 = "class C { int a; }"; var src2 = "class C { int a = 0; public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_InstanceCtorInsertExplicit() { var src1 = "class C { int a { get; } = 1; }"; var src2 = "class C { int a { get; } = 2; public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_GenericType() { var src1 = "class C<T> { int a = 1; }"; var src2 = "class C<T> { int a = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 1]@17 -> [a = 2]@17"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.GenericTypeUpdate, "a = 2"), Diagnostic(RudeEditKind.GenericTypeUpdate, "class C<T>")); } [Fact] public void PropertyInitializerUpdate_GenericType() { var src1 = "class C<T> { int a { get; } = 1; }"; var src2 = "class C<T> { int a { get; } = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.GenericTypeUpdate, "int a"), Diagnostic(RudeEditKind.GenericTypeUpdate, "class C<T>")); } [Fact] public void FieldInitializerUpdate_StackAllocInConstructor() { var src1 = "unsafe class C { int a = 1; public C() { int* a = stackalloc int[10]; } }"; var src2 = "unsafe class C { int a = 2; public C() { int* a = stackalloc int[10]; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 1]@21 -> [a = 2]@21"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", FeaturesResources.constructor)); } [Fact] [WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void FieldInitializerUpdate_SwitchExpressionInConstructor() { var src1 = "class C { int a = 1; public C() { var b = a switch { 0 => 0, _ => 1 }; } }"; var src2 = "class C { int a = 2; public C() { var b = a switch { 0 => 0, _ => 1 }; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void PropertyInitializerUpdate_StackAllocInConstructor1() { var src1 = "unsafe class C { int a { get; } = 1; public C() { int* a = stackalloc int[10]; } }"; var src2 = "unsafe class C { int a { get; } = 2; public C() { int* a = stackalloc int[10]; } }"; var edits = GetTopEdits(src1, src2); // TODO (tomat): diagnostic should point to the property initializer edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", FeaturesResources.constructor)); } [Fact] public void PropertyInitializerUpdate_StackAllocInConstructor2() { var src1 = "unsafe class C { int a { get; } = 1; public C() : this(1) { int* a = stackalloc int[10]; } public C(int a) { } }"; var src2 = "unsafe class C { int a { get; } = 2; public C() : this(1) { int* a = stackalloc int[10]; } public C(int a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void PropertyInitializerUpdate_StackAllocInConstructor3() { var src1 = "unsafe class C { int a { get; } = 1; public C() { } public C(int b) { int* a = stackalloc int[10]; } }"; var src2 = "unsafe class C { int a { get; } = 2; public C() { } public C(int b) { int* a = stackalloc int[10]; } }"; var edits = GetTopEdits(src1, src2); // TODO (tomat): diagnostic should point to the property initializer edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", FeaturesResources.constructor)); } [Fact] [WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void PropertyInitializerUpdate_SwitchExpressionInConstructor1() { var src1 = "class C { int a { get; } = 1; public C() { var b = a switch { 0 => 0, _ => 1 }; } }"; var src2 = "class C { int a { get; } = 2; public C() { var b = a switch { 0 => 0, _ => 1 }; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] [WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void PropertyInitializerUpdate_SwitchExpressionInConstructor2() { var src1 = "class C { int a { get; } = 1; public C() : this(1) { var b = a switch { 0 => 0, _ => 1 }; } public C(int a) { } }"; var src2 = "class C { int a { get; } = 2; public C() : this(1) { var b = a switch { 0 => 0, _ => 1 }; } public C(int a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] [WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void PropertyInitializerUpdate_SwitchExpressionInConstructor3() { var src1 = "class C { int a { get; } = 1; public C() { } public C(int b) { var b = a switch { 0 => 0, _ => 1 }; } }"; var src2 = "class C { int a { get; } = 2; public C() { } public C(int b) { var b = a switch { 0 => 0, _ => 1 }; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void FieldInitializerUpdate_LambdaInConstructor() { var src1 = "class C { int a = 1; public C() { F(() => {}); } static void F(System.Action a) {} }"; var src2 = "class C { int a = 2; public C() { F(() => {}); } static void F(System.Action a) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 1]@14 -> [a = 2]@14"); edits.VerifySemanticDiagnostics(); } [Fact] public void PropertyInitializerUpdate_LambdaInConstructor() { var src1 = "class C { int a { get; } = 1; public C() { F(() => {}); } static void F(System.Action a) {} }"; var src2 = "class C { int a { get; } = 2; public C() { F(() => {}); } static void F(System.Action a) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void FieldInitializerUpdate_QueryInConstructor() { var src1 = "using System.Linq; class C { int a = 1; public C() { F(from a in new[] {1,2,3} select a + 1); } static void F(System.Collections.Generic.IEnumerable<int> x) {} }"; var src2 = "using System.Linq; class C { int a = 2; public C() { F(from a in new[] {1,2,3} select a + 1); } static void F(System.Collections.Generic.IEnumerable<int> x) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 1]@33 -> [a = 2]@33"); edits.VerifySemanticDiagnostics(); } [Fact] public void PropertyInitializerUpdate_QueryInConstructor() { var src1 = "using System.Linq; class C { int a { get; } = 1; public C() { F(from a in new[] {1,2,3} select a + 1); } static void F(System.Collections.Generic.IEnumerable<int> x) {} }"; var src2 = "using System.Linq; class C { int a { get; } = 2; public C() { F(from a in new[] {1,2,3} select a + 1); } static void F(System.Collections.Generic.IEnumerable<int> x) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void FieldInitializerUpdate_AnonymousTypeInConstructor() { var src1 = "class C { int a = 1; C() { F(new { A = 1, B = 2 }); } static void F(object x) {} }"; var src2 = "class C { int a = 2; C() { F(new { A = 1, B = 2 }); } static void F(object x) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void PropertyInitializerUpdate_AnonymousTypeInConstructor() { var src1 = "class C { int a { get; } = 1; C() { F(new { A = 1, B = 2 }); } static void F(object x) {} }"; var src2 = "class C { int a { get; } = 2; C() { F(new { A = 1, B = 2 }); } static void F(object x) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void FieldInitializerUpdate_PartialTypeWithSingleDeclaration() { var src1 = "partial class C { int a = 1; }"; var src2 = "partial class C { int a = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 1]@22 -> [a = 2]@22"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_PartialTypeWithSingleDeclaration() { var src1 = "partial class C { int a { get; } = 1; }"; var src2 = "partial class C { int a { get; } = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_PartialTypeWithMultipleDeclarations() { var src1 = "partial class C { int a = 1; } partial class C { }"; var src2 = "partial class C { int a = 2; } partial class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 1]@22 -> [a = 2]@22"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_PartialTypeWithMultipleDeclarations() { var src1 = "partial class C { int a { get; } = 1; } partial class C { }"; var src2 = "partial class C { int a { get; } = 2; } partial class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_ParenthesizedLambda() { var src1 = "class C { int a = F(1, (x, y) => x + y); }"; var src2 = "class C { int a = F(2, (x, y) => x + y); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyInitializerUpdate_ParenthesizedLambda() { var src1 = "class C { int a { get; } = F(1, (x, y) => x + y); }"; var src2 = "class C { int a { get; } = F(2, (x, y) => x + y); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void FieldInitializerUpdate_SimpleLambda() { var src1 = "class C { int a = F(1, x => x); }"; var src2 = "class C { int a = F(2, x => x); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyInitializerUpdate_SimpleLambda() { var src1 = "class C { int a { get; } = F(1, x => x); }"; var src2 = "class C { int a { get; } = F(2, x => x); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void FieldInitializerUpdate_Query() { var src1 = "class C { int a = F(1, from goo in bar select baz); }"; var src2 = "class C { int a = F(2, from goo in bar select baz); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyInitializerUpdate_Query() { var src1 = "class C { int a { get; } = F(1, from goo in bar select baz); }"; var src2 = "class C { int a { get; } = F(2, from goo in bar select baz); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void FieldInitializerUpdate_AnonymousType() { var src1 = "class C { int a = F(1, new { A = 1, B = 2 }); }"; var src2 = "class C { int a = F(2, new { A = 1, B = 2 }); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyInitializerUpdate_AnonymousType() { var src1 = "class C { int a { get; } = F(1, new { A = 1, B = 2 }); }"; var src2 = "class C { int a { get; } = F(2, new { A = 1, B = 2 }); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void FieldInitializerUpdate_Lambdas_ImplicitCtor_EditInitializerWithLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 2</N:0.1>); } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_ImplicitCtor_EditInitializerWithoutLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = 1; int B = F(<N:0.0>b => b + 1</N:0.0>); } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = 2; int B = F(<N:0.0>b => b + 1</N:0.0>); } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_CtorIncludingInitializers_EditInitializerWithLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C() {} } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 2</N:0.1>); public C() {} } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_CtorIncludingInitializers_EditInitializerWithoutLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = 1; int B = F(<N:0.0>b => b + 1</N:0.0>); public C() {} } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = 2; int B = F(<N:0.0>b => b + 1</N:0.0>); public C() {} } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializers_EditInitializerWithLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) {} public C(bool b) {} } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 2</N:0.1>); public C(int a) {} public C(bool b) {} } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[0], syntaxMap[0]), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[1], syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializersContainingLambdas_EditInitializerWithLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(<N:0.3>d => d + 1</N:0.3>); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 2</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(<N:0.3>d => d + 1</N:0.3>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[0], syntaxMap[0]), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[1], syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializersContainingLambdas_EditInitializerWithLambda_Trivia1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(<N:0.3>d => d + 1</N:0.3>); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(<N:0.3>d => d + 1</N:0.3>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[0], syntaxMap[0]), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[1], syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializersContainingLambdas_EditConstructorWithLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(d => d + 1); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 2</N:0.2>); } public C(bool b) { F(d => d + 1); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Int32 a)"), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializersContainingLambdas_EditConstructorWithLambda_Trivia1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(d => d + 1); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(d => d + 1); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Int32 a)"), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializersContainingLambdas_EditConstructorWithoutLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(c => c + 1); } public C(bool b) { Console.WriteLine(1); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(c => c + 1); } public C(bool b) { Console.WriteLine(2); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Boolean b)"), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_EditConstructorNotIncludingInitializers() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(a => a + 1); int B = F(b => b + 1); public C(int a) { F(c => c + 1); } public C(bool b) : this(1) { Console.WriteLine(1); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(a => a + 1); int B = F(b => b + 1); public C(int a) { F(c => c + 1); } public C(bool b) : this(1) { Console.WriteLine(2); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Boolean b)")) }); } [Fact] public void FieldInitializerUpdate_Lambdas_RemoveCtorInitializer1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); unsafe public C(int a) { char* buffer = stackalloc char[16]; F(c => c + 1); } public C(bool b) : this(1) { Console.WriteLine(1); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); unsafe public C(int a) { char* buffer = stackalloc char[16]; F(c => c + 1); } public C(bool b) { Console.WriteLine(1); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Boolean b)"), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_AddCtorInitializer1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(a => a + 1); int B = F(b => b + 1); public C(int a) { F(c => c + 1); } public C(bool b) { Console.WriteLine(1); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(a => a + 1); int B = F(b => b + 1); public C(int a) { F(c => c + 1); } public C(bool b) : this(1) { Console.WriteLine(1); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Boolean b)")) }); } [Fact] public void FieldInitializerUpdate_Lambdas_UpdateBaseCtorInitializerWithLambdas1() { var src1 = @" using System; class B { public B(int a) { } } class C : B { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(bool b) : base(F(<N:0.2>c => c + 1</N:0.2>)) { F(<N:0.3>d => d + 1</N:0.3>); } } "; var src2 = @" using System; class B { public B(int a) { } } class C : B { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(bool b) : base(F(<N:0.2>c => c + 2</N:0.2>)) { F(<N:0.3>d => d + 1</N:0.3>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Boolean b)"), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_PartialDeclarationDelete_SingleDocument() { var src1 = @" partial class C { int x = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int y = F(<N:0.1>a => a + 10</N:0.1>); } partial class C { public C() { } static int F(Func<int, int> x) => 1; } "; var src2 = @" partial class C { int x = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int y = F(<N:0.1>a => a + 10</N:0.1>); static int F(Func<int, int> x) => 1; } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), syntaxMap[0]), }); } [Fact] public void FieldInitializerUpdate_ActiveStatements1() { var src1 = @" using System; class C { <AS:0>int A = <N:0.0>1</N:0.0>;</AS:0> int B = 1; public C(int a) { Console.WriteLine(1); } public C(bool b) { Console.WriteLine(1); } } "; var src2 = @" using System; class C { <AS:0>int A = <N:0.0>1</N:0.0>;</AS:0> int B = 2; public C(int a) { Console.WriteLine(1); } public C(bool b) { Console.WriteLine(1); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); var activeStatements = GetActiveStatements(src1, src2); edits.VerifySemantics( activeStatements, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[0], syntaxMap[0]), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[1], syntaxMap[0]), }); } [Fact] public void PropertyWithInitializer_SemanticError_Partial() { var src1 = @" partial class C { partial int P => 1; } partial class C { partial int P => 1; } "; var src2 = @" partial class C { partial int P => 1; } partial class C { partial int P => 2; public C() { } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(ActiveStatementsDescription.Empty, expectedSemanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => ((IPropertySymbol)c.GetMember<INamedTypeSymbol>("C").GetMembers("P").First()).GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void Field_Partial_DeleteInsert_InitializerRemoval() { var srcA1 = "partial class C { int F = 1; }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int F; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void Field_Partial_DeleteInsert_InitializerUpdate() { var srcA1 = "partial class C { int F = 1; }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int F = 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } #endregion #region Fields [Fact] public void Field_Rename() { var src1 = "class C { int a = 0; }"; var src2 = "class C { int b = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 0]@14 -> [b = 0]@14"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "b = 0", FeaturesResources.field)); } [Fact] public void Field_Kind_Update() { var src1 = "class C { Action a; }"; var src2 = "class C { event Action a; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Action a;]@10 -> [event Action a;]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.FieldKindUpdate, "event Action a", FeaturesResources.event_)); } [Theory] [InlineData("static")] [InlineData("volatile")] [InlineData("const")] public void Field_Modifiers_Update(string oldModifiers, string newModifiers = "") { if (oldModifiers != "") { oldModifiers += " "; } if (newModifiers != "") { newModifiers += " "; } var src1 = "class C { " + oldModifiers + "int F = 0; }"; var src2 = "class C { " + newModifiers + "int F = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [" + oldModifiers + "int F = 0;]@10 -> [" + newModifiers + "int F = 0;]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, newModifiers + "int F = 0", FeaturesResources.field)); } [Fact] public void Field_Modifier_Add_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int F; }"; var srcA2 = "partial class C { static int F; }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.ModifiersUpdate, "F", FeaturesResources.field) }), DocumentResults(), }); } [Fact] public void Field_Attribute_Add_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int F; }"; var srcA2 = "partial class C { [System.Obsolete]int F; }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")) }), DocumentResults(), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Field_FixedSize_Update() { var src1 = "struct S { public unsafe fixed byte a[1], b[2]; }"; var src2 = "struct S { public unsafe fixed byte a[2], b[3]; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a[1]]@36 -> [a[2]]@36", "Update [b[2]]@42 -> [b[3]]@42"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.FixedSizeFieldUpdate, "a[2]", FeaturesResources.field), Diagnostic(RudeEditKind.FixedSizeFieldUpdate, "b[3]", FeaturesResources.field)); } [WorkItem(1120407, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1120407")] [Fact] public void Field_Const_Update() { var src1 = "class C { const int x = 0; }"; var src2 = "class C { const int x = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [x = 0]@20 -> [x = 1]@20"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, "x = 1", FeaturesResources.const_field)); } [Fact] public void Field_Event_VariableDeclarator_Update() { var src1 = "class C { event Action a; }"; var src2 = "class C { event Action a = () => { }; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@23 -> [a = () => { }]@23"); edits.VerifyRudeDiagnostics(); } [Fact] public void Field_Reorder() { var src1 = "class C { int a = 0; int b = 1; int c = 2; }"; var src2 = "class C { int c = 2; int a = 0; int b = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [int c = 2;]@32 -> @10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "int c = 2", FeaturesResources.field)); } [Fact] public void Field_Insert() { var src1 = "class C { }"; var src2 = "class C { int a = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [int a = 1;]@10", "Insert [int a = 1]@10", "Insert [a = 1]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.a")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void Field_Insert_IntoStruct() { var src1 = @" struct S { public int a; public S(int z) { this = default(S); a = z; } } "; var src2 = @" struct S { public int a; private int b; private static int c; private static int f = 1; private event System.Action d; public S(int z) { this = default(S); a = z; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoStruct, "b", FeaturesResources.field, CSharpFeaturesResources.struct_), Diagnostic(RudeEditKind.InsertIntoStruct, "c", FeaturesResources.field, CSharpFeaturesResources.struct_), Diagnostic(RudeEditKind.InsertIntoStruct, "f = 1", FeaturesResources.field, CSharpFeaturesResources.struct_), Diagnostic(RudeEditKind.InsertIntoStruct, "d", CSharpFeaturesResources.event_field, CSharpFeaturesResources.struct_)); } [Fact] public void Field_Insert_IntoLayoutClass_Auto() { var src1 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Auto)] class C { private int a; } "; var src2 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Auto)] class C { private int a; private int b; private int c; private static int d; } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.b")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.c")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.d")), }); } [Fact] public void Field_Insert_IntoLayoutClass_Explicit() { var src1 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Explicit)] class C { [FieldOffset(0)] private int a; } "; var src2 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Explicit)] class C { [FieldOffset(0)] private int a; [FieldOffset(0)] private int b; [FieldOffset(4)] private int c; private static int d; } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "b", FeaturesResources.field, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "c", FeaturesResources.field, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "d", FeaturesResources.field, FeaturesResources.class_)); } [Fact] public void Field_Insert_IntoLayoutClass_Sequential() { var src1 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Sequential)] class C { private int a; } "; var src2 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Sequential)] class C { private int a; private int b; private int c; private static int d; } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "b", FeaturesResources.field, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "c", FeaturesResources.field, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "d", FeaturesResources.field, FeaturesResources.class_)); } [Fact] public void Field_Insert_WithInitializersAndLambdas1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); public C() { F(<N:0.1>c => c + 1</N:0.1>); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(b => b + 1); // new field public C() { F(<N:0.1>c => c + 1</N:0.1>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.B")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void Field_Insert_ConstructorReplacingImplicitConstructor_WithInitializersAndLambdas() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(b => b + 1); // new field public C() // new ctor replacing existing implicit constructor { F(c => c + 1); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.B")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact, WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")] public void Field_Insert_ParameterlessConstructorInsert_WithInitializersAndLambdas() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); public C(int x) {} } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); public C(int x) {} public C() // new ctor { F(c => c + 1); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, "public C()")); // TODO (bug https://github.com/dotnet/roslyn/issues/2504): //edits.VerifySemantics( // ActiveStatementsDescription.Empty, // new[] // { // SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<NamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) // }); } [Fact, WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")] public void Field_Insert_ConstructorInsert_WithInitializersAndLambdas1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(b => b + 1); // new field public C(int x) // new ctor { F(c => c + 1); } } "; var edits = GetTopEdits(src1, src2); _ = GetSyntaxMap(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, "public C(int x)")); // TODO (bug https://github.com/dotnet/roslyn/issues/2504): //edits.VerifySemantics( // ActiveStatementsDescription.Empty, // new[] // { // SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.B")), // SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<NamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) // }); } [Fact, WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")] public void Field_Insert_ConstructorInsert_WithInitializersButNoExistingLambdas1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(null); } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(null); int B = F(b => b + 1); // new field public C(int x) // new ctor { F(c => c + 1); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.B")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single()) }); } [Fact] public void Field_Insert_NotSupportedByRuntime() { var src1 = "class C { }"; var src2 = "class C { public int a = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities | EditAndContinueCapabilities.AddStaticFieldToExistingType, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "a = 1", FeaturesResources.field)); } [Fact] public void Field_Insert_Static_NotSupportedByRuntime() { var src1 = "class C { }"; var src2 = "class C { public static int a = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities | EditAndContinueCapabilities.AddInstanceFieldToExistingType, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "a = 1", FeaturesResources.field)); } [Fact] public void Field_Attribute_Add_NotSupportedByRuntime() { var src1 = @" class C { public int a = 1, x = 1; }"; var src2 = @" class C { [System.Obsolete]public int a = 1, x = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public int a = 1, x = 1;]@18 -> [[System.Obsolete]public int a = 1, x = 1;]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "public int a = 1, x = 1", FeaturesResources.field), Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "public int a = 1, x = 1", FeaturesResources.field)); } [Fact] public void Field_Attribute_Add() { var src1 = @" class C { public int a, b; }"; var src2 = @" class C { [System.Obsolete]public int a, b; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.a")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.b")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Field_Attribute_Add_WithInitializer() { var src1 = @" class C { int a; }"; var src2 = @" class C { [System.Obsolete]int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.a")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Field_Attribute_DeleteInsertUpdate_WithInitializer() { var srcA1 = "partial class C { int a = 1; }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { [System.Obsolete]int a = 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.a"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Field_Delete1() { var src1 = "class C { int a = 1; }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [int a = 1;]@10", "Delete [int a = 1]@10", "Delete [a = 1]@14"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.field, "a"))); } [Fact] public void Field_UnsafeModifier_Update() { var src1 = "struct Node { unsafe Node* left; }"; var src2 = "struct Node { Node* left; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [unsafe Node* left;]@14 -> [Node* left;]@14"); edits.VerifyRudeDiagnostics(); } [Fact] public void Field_ModifierAndType_Update() { var src1 = "struct Node { unsafe Node* left; }"; var src2 = "struct Node { Node left; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [unsafe Node* left;]@14 -> [Node left;]@14", "Update [Node* left]@21 -> [Node left]@14"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "Node left", FeaturesResources.field)); } [Theory] [InlineData("string", "string?")] [InlineData("object", "dynamic")] [InlineData("(int a, int b)", "(int a, int c)")] public void Field_Type_Update_RuntimeTypeUnchanged(string oldType, string newType) { var src1 = "class C { " + oldType + " F, G; }"; var src2 = "class C { " + newType + " F, G; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.G"))); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void Field_Type_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C { " + oldType + " F, G; }"; var src2 = "class C { " + newType + " F, G; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, newType + " F, G", FeaturesResources.field), Diagnostic(RudeEditKind.TypeUpdate, newType + " F, G", FeaturesResources.field)); } [Theory] [InlineData("string", "string?")] [InlineData("object", "dynamic")] [InlineData("(int a, int b)", "(int a, int c)")] public void Field_Event_Type_Update_RuntimeTypeUnchanged(string oldType, string newType) { var src1 = "class C { event System.Action<" + oldType + "> F, G; }"; var src2 = "class C { event System.Action<" + newType + "> F, G; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.G"))); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void Field_Event_Type_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C { event System.Action<" + oldType + "> F, G; }"; var src2 = "class C { event System.Action<" + newType + "> F, G; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "event System.Action<" + newType + "> F, G", FeaturesResources.event_), Diagnostic(RudeEditKind.TypeUpdate, "event System.Action<" + newType + "> F, G", FeaturesResources.event_)); } [Fact] public void Field_Type_Update_ReorderRemoveAdd() { var src1 = "class C { int F, G, H; bool U; }"; var src2 = "class C { string G, F; double V, U; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int F, G, H]@10 -> [string G, F]@10", "Reorder [G]@17 -> @17", "Update [bool U]@23 -> [double V, U]@23", "Insert [V]@30", "Delete [H]@20"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "G", FeaturesResources.field), Diagnostic(RudeEditKind.TypeUpdate, "string G, F", FeaturesResources.field), Diagnostic(RudeEditKind.TypeUpdate, "string G, F", FeaturesResources.field), Diagnostic(RudeEditKind.TypeUpdate, "double V, U", FeaturesResources.field), Diagnostic(RudeEditKind.Delete, "string G, F", DeletedSymbolDisplay(FeaturesResources.field, "H"))); } [Fact] public void Field_Event_Reorder() { var src1 = "class C { int a = 0; int b = 1; event int c = 2; }"; var src2 = "class C { event int c = 2; int a = 0; int b = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [event int c = 2;]@32 -> @10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "event int c = 2", CSharpFeaturesResources.event_field)); } [Fact] public void Field_Event_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { event int E = 2; }"; var srcA2 = "partial class C { event int E = 2; }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults(), }); } #endregion #region Properties [Theory] [InlineData("static")] [InlineData("virtual")] [InlineData("abstract")] [InlineData("override")] [InlineData("sealed override", "override")] public void Property_Modifiers_Update(string oldModifiers, string newModifiers = "") { if (oldModifiers != "") { oldModifiers += " "; } if (newModifiers != "") { newModifiers += " "; } var src1 = "class C { " + oldModifiers + "int F => 0; }"; var src2 = "class C { " + newModifiers + "int F => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [" + oldModifiers + "int F => 0;]@10 -> [" + newModifiers + "int F => 0;]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, newModifiers + "int F", FeaturesResources.property_)); } [Fact] public void Property_ExpressionBody_Rename() { var src1 = "class C { int P => 1; }"; var src2 = "class C { int Q => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "int Q", FeaturesResources.property_)); } [Fact] public void Property_ExpressionBody_Update() { var src1 = "class C { int P => 1; }"; var src2 = "class C { int P => 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [int P => 1;]@10 -> [int P => 2;]@10"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false) }); } [Fact, WorkItem(48628, "https://github.com/dotnet/roslyn/issues/48628")] public void Property_ExpressionBody_ModifierUpdate() { var src1 = "class C { int P => 1; }"; var src2 = "class C { unsafe int P => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [int P => 1;]@10 -> [unsafe int P => 1;]@10"); edits.VerifyRudeDiagnostics(); } [Fact] public void Property_ExpressionBodyToBlockBody1() { var src1 = "class C { int P => 1; }"; var src2 = "class C { int P { get { return 2; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P => 1;]@10 -> [int P { get { return 2; } }]@10", "Insert [{ get { return 2; } }]@16", "Insert [get { return 2; }]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false) }); } [Fact] public void Property_ExpressionBodyToBlockBody2() { var src1 = "class C { int P => 1; }"; var src2 = "class C { int P { get { return 2; } set { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P => 1;]@10 -> [int P { get { return 2; } set { } }]@10", "Insert [{ get { return 2; } set { } }]@16", "Insert [get { return 2; }]@18", "Insert [set { }]@36"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.set_P"), preserveLocalVariables: false) }); } [Fact] public void Property_BlockBodyToExpressionBody1() { var src1 = "class C { int P { get { return 2; } } }"; var src2 = "class C { int P => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P { get { return 2; } }]@10 -> [int P => 1;]@10", "Delete [{ get { return 2; } }]@16", "Delete [get { return 2; }]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false) }); } [Fact] public void Property_BlockBodyToExpressionBody2() { var src1 = "class C { int P { get { return 2; } set { } } }"; var src2 = "class C { int P => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P { get { return 2; } set { } }]@10 -> [int P => 1;]@10", "Delete [{ get { return 2; } set { } }]@16", "Delete [get { return 2; }]@18", "Delete [set { }]@36"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_setter, "P.set"))); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_ExpressionBodyToGetterExpressionBody() { var src1 = "class C { int P => 1; }"; var src2 = "class C { int P { get => 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P => 1;]@10 -> [int P { get => 2; }]@10", "Insert [{ get => 2; }]@16", "Insert [get => 2;]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_GetterExpressionBodyToExpressionBody() { var src1 = "class C { int P { get => 2; } }"; var src2 = "class C { int P => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P { get => 2; }]@10 -> [int P => 1;]@10", "Delete [{ get => 2; }]@16", "Delete [get => 2;]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_GetterBlockBodyToGetterExpressionBody() { var src1 = "class C { int P { get { return 2; } } }"; var src2 = "class C { int P { get => 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get { return 2; }]@18 -> [get => 2;]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_SetterBlockBodyToSetterExpressionBody() { var src1 = "class C { int P { set { } } }"; var src2 = "class C { int P { set => F(); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [set { }]@18 -> [set => F();]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_InitBlockBodyToInitExpressionBody() { var src1 = "class C { int P { init { } } }"; var src2 = "class C { int P { init => F(); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [init { }]@18 -> [init => F();]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod, preserveLocalVariables: false), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_GetterExpressionBodyToGetterBlockBody() { var src1 = "class C { int P { get => 2; } }"; var src2 = "class C { int P { get { return 2; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get => 2;]@18 -> [get { return 2; }]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_GetterBlockBodyWithSetterToGetterExpressionBodyWithSetter() { var src1 = "class C { int P { get => 2; set { Console.WriteLine(0); } } }"; var src2 = "class C { int P { get { return 2; } set { Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get => 2;]@18 -> [get { return 2; }]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_GetterExpressionBodyWithSetterToGetterBlockBodyWithSetter() { var src1 = "class C { int P { get { return 2; } set { Console.WriteLine(0); } } }"; var src2 = "class C { int P { get => 2; set { Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get { return 2; }]@18 -> [get => 2;]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_P"), preserveLocalVariables: false) }); } [Fact] public void Property_Rename1() { var src1 = "class C { int P { get { return 1; } } }"; var src2 = "class C { int Q { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "int Q", FeaturesResources.property_)); } [Fact] public void Property_Rename2() { var src1 = "class C { int I.P { get { return 1; } } }"; var src2 = "class C { int J.P { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "int J.P", FeaturesResources.property_)); } [Fact] public void Property_RenameAndUpdate() { var src1 = "class C { int P { get { return 1; } } }"; var src2 = "class C { int Q { get { return 2; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "int Q", FeaturesResources.property_)); } [Fact] public void PropertyDelete() { var src1 = "class C { int P { get { return 1; } } }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.property_, "P"))); } [Fact] public void PropertyReorder1() { var src1 = "class C { int P { get { return 1; } } int Q { get { return 1; } } }"; var src2 = "class C { int Q { get { return 1; } } int P { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [int Q { get { return 1; } }]@38 -> @10"); // TODO: we can allow the move since the property doesn't have a backing field edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "int Q", FeaturesResources.property_)); } [Fact] public void PropertyReorder2() { var src1 = "class C { int P { get; set; } int Q { get; set; } }"; var src2 = "class C { int Q { get; set; } int P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [int Q { get; set; }]@30 -> @10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "int Q", FeaturesResources.auto_property)); } [Fact] public void PropertyAccessorReorder_GetSet() { var src1 = "class C { int P { get { return 1; } set { } } }"; var src2 = "class C { int P { set { } get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [set { }]@36 -> @18"); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyAccessorReorder_GetInit() { var src1 = "class C { int P { get { return 1; } init { } } }"; var src2 = "class C { int P { init { } get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [init { }]@36 -> @18"); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyTypeUpdate() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { char P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P { get; set; }]@10 -> [char P { get; set; }]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "char P", FeaturesResources.property_)); } [Fact] public void PropertyUpdate_AddAttribute() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { [System.Obsolete]int P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int P", FeaturesResources.property_)); } [Fact] public void PropertyUpdate_AddAttribute_SupportedByRuntime() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { [System.Obsolete]int P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.P")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void PropertyAccessorUpdate_AddAttribute() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { int P { [System.Obsolete]get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "get", CSharpFeaturesResources.property_getter)); } [Fact] public void PropertyAccessorUpdate_AddAttribute2() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { int P { get; [System.Obsolete]set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "set", CSharpFeaturesResources.property_setter)); } [Fact] public void PropertyAccessorUpdate_AddAttribute_SupportedByRuntime() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { int P { [System.Obsolete]get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void PropertyAccessorUpdate_AddAttribute_SupportedByRuntime2() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { int P { get; [System.Obsolete]set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void PropertyInsert() { var src1 = "class C { }"; var src2 = "class C { int P { get => 1; set { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").GetMember("P"))); } [Fact] public void PropertyInsert_NotSupportedByRuntime() { var src1 = "class C { }"; var src2 = "class C { int P { get => 1; set { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "int P", FeaturesResources.auto_property)); } [WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] [Fact] public void PropertyInsert_PInvoke() { var src1 = @" using System; using System.Runtime.InteropServices; class C { }"; var src2 = @" using System; using System.Runtime.InteropServices; class C { private static extern int P1 { [DllImport(""x.dll"")]get; } private static extern int P2 { [DllImport(""x.dll"")]set; } private static extern int P3 { [DllImport(""x.dll"")]get; [DllImport(""x.dll"")]set; } } "; var edits = GetTopEdits(src1, src2); // CLR doesn't support methods without a body edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertExtern, "private static extern int P1", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertExtern, "private static extern int P2", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertExtern, "private static extern int P3", FeaturesResources.property_)); } [Fact] public void PropertyInsert_IntoStruct() { var src1 = @" struct S { public int a; public S(int z) { a = z; } } "; var src2 = @" struct S { public int a; private static int c { get; set; } private static int e { get { return 0; } set { } } private static int g { get; } = 1; private static int i { get; set; } = 1; private static int k => 1; public S(int z) { a = z; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoStruct, "private static int c { get; set; }", FeaturesResources.auto_property, CSharpFeaturesResources.struct_), Diagnostic(RudeEditKind.InsertIntoStruct, "private static int g { get; } = 1;", FeaturesResources.auto_property, CSharpFeaturesResources.struct_), Diagnostic(RudeEditKind.InsertIntoStruct, "private static int i { get; set; } = 1;", FeaturesResources.auto_property, CSharpFeaturesResources.struct_)); } [Fact] public void PropertyInsert_IntoLayoutClass_Sequential() { var src1 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Sequential)] class C { private int a; } "; var src2 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Sequential)] class C { private int a; private int b { get; set; } private static int c { get; set; } private int d { get { return 0; } set { } } private static int e { get { return 0; } set { } } private int f { get; } = 1; private static int g { get; } = 1; private int h { get; set; } = 1; private static int i { get; set; } = 1; private int j => 1; private static int k => 1; } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private int b { get; set; }", FeaturesResources.auto_property, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private static int c { get; set; }", FeaturesResources.auto_property, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private int f { get; } = 1;", FeaturesResources.auto_property, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private static int g { get; } = 1;", FeaturesResources.auto_property, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private int h { get; set; } = 1;", FeaturesResources.auto_property, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private static int i { get; set; } = 1;", FeaturesResources.auto_property, FeaturesResources.class_)); } // Design: Adding private accessors should also be allowed since we now allow adding private methods // and adding public properties and/or public accessors are not allowed. [Fact] public void PrivateProperty_AccessorAdd() { var src1 = "class C { int _p; int P { get { return 1; } } }"; var src2 = "class C { int _p; int P { get { return 1; } set { _p = value; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [set { _p = value; }]@44"); edits.VerifyRudeDiagnostics(); } [WorkItem(755975, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755975")] [Fact] public void PrivatePropertyAccessorDelete() { var src1 = "class C { int _p; int P { get { return 1; } set { _p = value; } } }"; var src2 = "class C { int _p; int P { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [set { _p = value; }]@44"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_setter, "P.set"))); } [Fact] public void PrivateAutoPropertyAccessorAdd1() { var src1 = "class C { int P { get; } }"; var src2 = "class C { int P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [set;]@23"); edits.VerifyRudeDiagnostics(); } [Fact] public void PrivateAutoPropertyAccessorAdd2() { var src1 = "class C { public int P { get; } }"; var src2 = "class C { public int P { get; private set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [private set;]@30"); edits.VerifyRudeDiagnostics(); } [Fact] public void PrivateAutoPropertyAccessorAdd4() { var src1 = "class C { public int P { get; } }"; var src2 = "class C { public int P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [set;]@30"); edits.VerifyRudeDiagnostics(); } [Fact] public void PrivateAutoPropertyAccessorAdd5() { var src1 = "class C { public int P { get; } }"; var src2 = "class C { public int P { get; internal set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [internal set;]@30"); edits.VerifyRudeDiagnostics(); } [Fact] public void PrivateAutoPropertyAccessorAdd6() { var src1 = "class C { int P { get; } = 1; }"; var src2 = "class C { int P { get; set; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [set;]@23"); edits.VerifyRudeDiagnostics(); } [Fact] public void PrivateAutoPropertyAccessorAdd_Init() { var src1 = "class C { int P { get; } = 1; }"; var src2 = "class C { int P { get; init; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [init;]@23"); edits.VerifyRudeDiagnostics(); } [WorkItem(755975, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755975")] [Fact] public void PrivateAutoPropertyAccessorDelete_Get() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { int P { set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [get;]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_getter, "P.get"))); } [Fact] public void AutoPropertyAccessor_SetToInit() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { int P { get; init; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [set;]@23 -> [init;]@23"); // not allowed since it changes the backing field readonly-ness and the signature of the setter (modreq) edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.AccessorKindUpdate, "init", CSharpFeaturesResources.property_setter)); } [Fact] public void AutoPropertyAccessor_InitToSet() { var src1 = "class C { int P { get; init; } }"; var src2 = "class C { int P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [init;]@23 -> [set;]@23"); // not allowed since it changes the backing field readonly-ness and the signature of the setter (modreq) edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.AccessorKindUpdate, "set", CSharpFeaturesResources.property_setter)); } [Fact] public void PrivateAutoPropertyAccessorDelete_Set() { var src1 = "class C { int P { get; set; } = 1; }"; var src2 = "class C { int P { get; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [set;]@23"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_setter, "P.set"))); } [Fact] public void PrivateAutoPropertyAccessorDelete_Init() { var src1 = "class C { int P { get; init; } = 1; }"; var src2 = "class C { int P { get; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [init;]@23"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_setter, "P.init"))); } [Fact] public void AutoPropertyAccessorUpdate() { var src1 = "class C { int P { get; } }"; var src2 = "class C { int P { set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get;]@18 -> [set;]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.AccessorKindUpdate, "set", CSharpFeaturesResources.property_setter)); } [WorkItem(992578, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/992578")] [Fact] public void InsertIncompleteProperty() { var src1 = "class C { }"; var src2 = "class C { public int P { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [public int P { }]@10", "Insert [{ }]@23"); edits.VerifyRudeDiagnostics(); } [Fact] public void Property_ReadOnlyRef_Insert() { var src1 = "class Test { }"; var src2 = "class Test { ref readonly int P { get; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [ref readonly int P { get; }]@13", "Insert [{ get; }]@32", "Insert [get;]@34"); edits.VerifyRudeDiagnostics(); } [Fact] public void Property_ReadOnlyRef_Update() { var src1 = "class Test { int P { get; } }"; var src2 = "class Test { ref readonly int P { get; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P { get; }]@13 -> [ref readonly int P { get; }]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "ref readonly int P", FeaturesResources.property_)); } [Fact] public void Property_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int P { get => 1; set { } } }"; var srcA2 = "partial class C { int P { get => 1; set { } } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod) }), DocumentResults(), }); } [Fact] public void PropertyInit_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int Q { get => 1; init { } }}"; var srcA2 = "partial class C { int Q { get => 1; init { } }}"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("Q").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("Q").SetMethod) }), DocumentResults(), }); } [Fact] public void AutoProperty_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int P { get; set; } int Q { get; init; } }"; var srcA2 = "partial class C { int P { get; set; } int Q { get; init; } }"; var srcB2 = "partial class C { }"; // Accessors need to be updated even though they do not have an explicit body. // There is still a sequence point generated for them whose location needs to be updated. EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("Q").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("Q").SetMethod), }), DocumentResults(), }); } [Fact] public void AutoPropertyWithInitializer_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int P { get; set; } = 1; }"; var srcA2 = "partial class C { int P { get; set; } = 1; }"; var srcB2 = "partial class C { }"; // Accessors need to be updated even though they do not have an explicit body. // There is still a sequence point generated for them whose location needs to be updated. EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults(), }); } [Fact] public void PropertyWithExpressionBody_Partial_InsertDeleteUpdate() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int P => 1; }"; var srcA2 = "partial class C { int P => 2; }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod) }), DocumentResults(), }); } [Fact] public void AutoProperty_ReadOnly_Add() { var src1 = @" struct S { int P { get; } }"; var src2 = @" struct S { readonly int P { get; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Property_InMutableStruct_ReadOnly_Add() { var src1 = @" struct S { int P1 { get => 1; } int P2 { get => 1; set {}} int P3 { get => 1; set {}} int P4 { get => 1; set {}} }"; var src2 = @" struct S { readonly int P1 { get => 1; } int P2 { readonly get => 1; set {}} int P3 { get => 1; readonly set {}} readonly int P4 { get => 1; set {}} }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int P1", CSharpFeaturesResources.property_getter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int P4", CSharpFeaturesResources.property_getter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int P4", CSharpFeaturesResources.property_setter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly get", CSharpFeaturesResources.property_getter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly set", CSharpFeaturesResources.property_setter)); } [Fact] public void Property_InReadOnlyStruct_ReadOnly_Add() { // indent to align accessor bodies and avoid updates caused by sequence point location changes var src1 = @" readonly struct S { int P1 { get => 1; } int P2 { get => 1; set {}} int P3 { get => 1; set {}} int P4 { get => 1; set {}} }"; var src2 = @" readonly struct S { readonly int P1 { get => 1; } int P2 { readonly get => 1; set {}} int P3 { get => 1; readonly set {}} readonly int P4 { get => 1; set {}} }"; var edits = GetTopEdits(src1, src2); // updates only for accessors whose modifiers were explicitly updated edits.VerifySemantics(new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember<IPropertySymbol>("P2").GetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember<IPropertySymbol>("P3").SetMethod, preserveLocalVariables: false) }); } #endregion #region Indexers [Theory] [InlineData("virtual")] [InlineData("abstract")] [InlineData("override")] [InlineData("sealed override", "override")] public void Indexer_Modifiers_Update(string oldModifiers, string newModifiers = "") { if (oldModifiers != "") { oldModifiers += " "; } if (newModifiers != "") { newModifiers += " "; } var src1 = "class C { " + oldModifiers + "int this[int a] => 0; }"; var src2 = "class C { " + newModifiers + "int this[int a] => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [" + oldModifiers + "int this[int a] => 0;]@10 -> [" + newModifiers + "int this[int a] => 0;]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, newModifiers + "int this[int a]", FeaturesResources.indexer_)); } [Fact] public void Indexer_GetterUpdate() { var src1 = "class C { int this[int a] { get { return 1; } } }"; var src2 = "class C { int this[int a] { get { return 2; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [get { return 1; }]@28 -> [get { return 2; }]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact] public void Indexer_SetterUpdate() { var src1 = "class C { int this[int a] { get { return 1; } set { System.Console.WriteLine(value); } } }"; var src2 = "class C { int this[int a] { get { return 1; } set { System.Console.WriteLine(value + 1); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [set { System.Console.WriteLine(value); }]@46 -> [set { System.Console.WriteLine(value + 1); }]@46"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item"), preserveLocalVariables: false) }); } [Fact] public void Indexer_InitUpdate() { var src1 = "class C { int this[int a] { get { return 1; } init { System.Console.WriteLine(value); } } }"; var src2 = "class C { int this[int a] { get { return 1; } init { System.Console.WriteLine(value + 1); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [init { System.Console.WriteLine(value); }]@46 -> [init { System.Console.WriteLine(value + 1); }]@46"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item"), preserveLocalVariables: false) }); } [Fact] public void IndexerWithExpressionBody_Update() { var src1 = "class C { int this[int a] => 1; }"; var src2 = "class C { int this[int a] => 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => 1;]@10 -> [int this[int a] => 2;]@10"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")] public void IndexerWithExpressionBody_Update_LiftedParameter() { var src1 = @" using System; class C { int this[int a] => new Func<int>(() => a + 1)() + 10; } "; var src2 = @" using System; class C { int this[int a] => new Func<int>(() => 2)() + 11; // not capturing a anymore }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => new Func<int>(() => a + 1)() + 10;]@35 -> [int this[int a] => new Func<int>(() => 2)() + 11;]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a")); } [Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")] public void IndexerWithExpressionBody_Update_LiftedParameter_2() { var src1 = @" using System; class C { int this[int a] => new Func<int>(() => a + 1)(); } "; var src2 = @" using System; class C { int this[int a] => new Func<int>(() => 2)(); // not capturing a anymore }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => new Func<int>(() => a + 1)();]@35 -> [int this[int a] => new Func<int>(() => 2)();]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a")); } [Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")] public void IndexerWithExpressionBody_Update_LiftedParameter_3() { var src1 = @" using System; class C { int this[int a] => new Func<int>(() => { return a + 1; })(); } "; var src2 = @" using System; class C { int this[int a] => new Func<int>(() => { return 2; })(); // not capturing a anymore }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => new Func<int>(() => { return a + 1; })();]@35 -> [int this[int a] => new Func<int>(() => { return 2; })();]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a")); } [Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")] public void IndexerWithExpressionBody_Update_LiftedParameter_4() { var src1 = @" using System; class C { int this[int a] => new Func<int>(delegate { return a + 1; })(); } "; var src2 = @" using System; class C { int this[int a] => new Func<int>(delegate { return 2; })(); // not capturing a anymore }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => new Func<int>(delegate { return a + 1; })();]@35 -> [int this[int a] => new Func<int>(delegate { return 2; })();]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a")); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_ExpressionBodyToBlockBody() { var src1 = "class C { int this[int a] => 1; }"; var src2 = "class C { int this[int a] { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => 1;]@10 -> [int this[int a] { get { return 1; } }]@10", "Insert [{ get { return 1; } }]@26", "Insert [get { return 1; }]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_BlockBodyToExpressionBody() { var src1 = "class C { int this[int a] { get { return 1; } } }"; var src2 = "class C { int this[int a] => 1; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] { get { return 1; } }]@10 -> [int this[int a] => 1;]@10", "Delete [{ get { return 1; } }]@26", "Delete [get { return 1; }]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_GetterExpressionBodyToBlockBody() { var src1 = "class C { int this[int a] { get => 1; } }"; var src2 = "class C { int this[int a] { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get => 1;]@28 -> [get { return 1; }]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_BlockBodyToGetterExpressionBody() { var src1 = "class C { int this[int a] { get { return 1; } } }"; var src2 = "class C { int this[int a] { get => 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get { return 1; }]@28 -> [get => 1;]@28"); edits.VerifyRudeDiagnostics(); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_GetterExpressionBodyToExpressionBody() { var src1 = "class C { int this[int a] { get => 1; } }"; var src2 = "class C { int this[int a] => 1; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] { get => 1; }]@10 -> [int this[int a] => 1;]@10", "Delete [{ get => 1; }]@26", "Delete [get => 1;]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_ExpressionBodyToGetterExpressionBody() { var src1 = "class C { int this[int a] => 1; }"; var src2 = "class C { int this[int a] { get => 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => 1;]@10 -> [int this[int a] { get => 1; }]@10", "Insert [{ get => 1; }]@26", "Insert [get => 1;]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_GetterBlockBodyToGetterExpressionBody() { var src1 = "class C { int this[int a] { get { return 1; } set { Console.WriteLine(0); } } }"; var src2 = "class C { int this[int a] { get => 1; set { Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get { return 1; }]@28 -> [get => 1;]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_SetterBlockBodyToSetterExpressionBody() { var src1 = "class C { int this[int a] { set { } } void F() { } }"; var src2 = "class C { int this[int a] { set => F(); } void F() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [set { }]@28 -> [set => F();]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_InitBlockBodyToInitExpressionBody() { var src1 = "class C { int this[int a] { init { } } void F() { } }"; var src2 = "class C { int this[int a] { init => F(); } void F() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [init { }]@28 -> [init => F();]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_GetterExpressionBodyToGetterBlockBody() { var src1 = "class C { int this[int a] { get => 1; set { Console.WriteLine(0); } } }"; var src2 = "class C { int this[int a] { get { return 1; } set { Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get => 1;]@28 -> [get { return 1; }]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_GetterAndSetterBlockBodiesToExpressionBody() { var src1 = "class C { int this[int a] { get { return 1; } set { Console.WriteLine(0); } } }"; var src2 = "class C { int this[int a] => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] { get { return 1; } set { Console.WriteLine(0); } }]@10 -> [int this[int a] => 1;]@10", "Delete [{ get { return 1; } set { Console.WriteLine(0); } }]@26", "Delete [get { return 1; }]@28", "Delete [set { Console.WriteLine(0); }]@46"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "int this[int a]", DeletedSymbolDisplay(CSharpFeaturesResources.indexer_setter, "this[int a].set"))); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_ExpressionBodyToGetterAndSetterBlockBodies() { var src1 = "class C { int this[int a] => 1; }"; var src2 = "class C { int this[int a] { get { return 1; } set { Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => 1;]@10 -> [int this[int a] { get { return 1; } set { Console.WriteLine(0); } }]@10", "Insert [{ get { return 1; } set { Console.WriteLine(0); } }]@26", "Insert [get { return 1; }]@28", "Insert [set { Console.WriteLine(0); }]@46"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.set_Item"), preserveLocalVariables: false) }); } [Fact] public void Indexer_Rename() { var src1 = "class C { int I.this[int a] { get { return 1; } } }"; var src2 = "class C { int J.this[int a] { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "int J.this[int a]", CSharpFeaturesResources.indexer)); } [Fact] public void Indexer_Reorder1() { var src1 = "class C { int this[int a] { get { return 1; } } int this[string a] { get { return 1; } } }"; var src2 = "class C { int this[string a] { get { return 1; } } int this[int a] { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [int this[string a] { get { return 1; } }]@48 -> @10"); edits.VerifyRudeDiagnostics(); } [Fact] public void Indexer_AccessorReorder() { var src1 = "class C { int this[int a] { get { return 1; } set { } } }"; var src2 = "class C { int this[int a] { set { } get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [set { }]@46 -> @28"); edits.VerifyRudeDiagnostics(); } [Fact] public void Indexer_TypeUpdate() { var src1 = "class C { int this[int a] { get; set; } }"; var src2 = "class C { string this[int a] { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] { get; set; }]@10 -> [string this[int a] { get; set; }]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "string this[int a]", CSharpFeaturesResources.indexer)); } [Fact] public void Tuple_TypeUpdate() { var src1 = "class C { (int, int) M() { throw new System.Exception(); } }"; var src2 = "class C { (string, int) M() { throw new System.Exception(); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int, int) M() { throw new System.Exception(); }]@10 -> [(string, int) M() { throw new System.Exception(); }]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "(string, int) M()", FeaturesResources.method)); } [Fact] public void TupleElementDelete() { var src1 = "class C { (int, int, int a) M() { return (1, 2, 3); } }"; var src2 = "class C { (int, int) M() { return (1, 2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int, int, int a) M() { return (1, 2, 3); }]@10 -> [(int, int) M() { return (1, 2); }]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "(int, int) M()", FeaturesResources.method)); } [Fact] public void TupleElementAdd() { var src1 = "class C { (int, int) M() { return (1, 2); } }"; var src2 = "class C { (int, int, int a) M() { return (1, 2, 3); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int, int) M() { return (1, 2); }]@10 -> [(int, int, int a) M() { return (1, 2, 3); }]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "(int, int, int a) M()", FeaturesResources.method)); } [Fact] public void Indexer_ParameterUpdate() { var src1 = "class C { int this[int a] { get; set; } }"; var src2 = "class C { int this[string a] { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "string a", FeaturesResources.parameter)); } [Fact] public void Indexer_AddGetAccessor() { var src1 = @" class Test { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); stringCollection[0] = ""hello""; } } class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { set { arr[i] = value; } } }"; var src2 = @" class Test { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); stringCollection[0] = ""hello""; } } class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { get { return arr[i]; } set { arr[i] = value; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [get { return arr[i]; }]@304"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InsertIntoGenericType, "get", CSharpFeaturesResources.indexer_getter)); } [Fact] public void Indexer_AddSetAccessor() { var src1 = @" class C { public int this[int i] { get { return default; } } }"; var src2 = @" class C { public int this[int i] { get { return default; } set { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [set { }]@67"); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").SetMethod)); } [Fact] public void Indexer_AddSetAccessor_GenericType() { var src1 = @" class C<T> { public T this[int i] { get { return default; } } }"; var src2 = @" class C<T> { public T this[int i] { get { return default; } set { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [set { }]@68"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoGenericType, "set", CSharpFeaturesResources.indexer_setter)); } [WorkItem(750109, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/750109")] [Fact] public void Indexer_DeleteGetAccessor() { var src1 = @" class C<T> { public T this[int i] { get { return arr[i]; } set { arr[i] = value; } } }"; var src2 = @" class C<T> { public T this[int i] { set { arr[i] = value; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [get { return arr[i]; }]@58"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "public T this[int i]", DeletedSymbolDisplay(CSharpFeaturesResources.indexer_getter, "this[int i].get"))); } [Fact] public void Indexer_DeleteSetAccessor() { var src1 = @" class C { public int this[int i] { get { return 0; } set { } } }"; var src2 = @" class C { public int this[int i] { get { return 0; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [set { }]@61"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "public int this[int i]", DeletedSymbolDisplay(CSharpFeaturesResources.indexer_setter, "this[int i].set"))); } [Fact, WorkItem(1174850, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1174850")] public void Indexer_Insert() { var src1 = "struct C { }"; var src2 = "struct C { public int this[int x, int y] { get { return x + y; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Indexer_ReadOnlyRef_Parameter_InsertWhole() { var src1 = "class Test { }"; var src2 = "class Test { int this[in int i] => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [int this[in int i] => throw null;]@13", "Insert [[in int i]]@21", "Insert [in int i]@22"); edits.VerifyRudeDiagnostics(); } [Fact] public void Indexer_ReadOnlyRef_Parameter_Update() { var src1 = "class Test { int this[int i] => throw null; }"; var src2 = "class Test { int this[in int i] => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int i]@22 -> [in int i]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "in int i", FeaturesResources.parameter)); } [Fact] public void Indexer_ReadOnlyRef_ReturnType_Insert() { var src1 = "class Test { }"; var src2 = "class Test { ref readonly int this[int i] => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [ref readonly int this[int i] => throw null;]@13", "Insert [[int i]]@34", "Insert [int i]@35"); edits.VerifyRudeDiagnostics(); } [Fact] public void Indexer_ReadOnlyRef_ReturnType_Update() { var src1 = "class Test { int this[int i] => throw null; }"; var src2 = "class Test { ref readonly int this[int i] => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int i] => throw null;]@13 -> [ref readonly int this[int i] => throw null;]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "ref readonly int this[int i]", FeaturesResources.indexer_)); } [Fact] public void Indexer_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int this[int x] { get => 1; set { } } }"; var srcA2 = "partial class C { int this[int x] { get => 1; set { } } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").SetMethod) }), DocumentResults(), }); } [Fact] public void IndexerInit_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int this[int x] { get => 1; init { } }}"; var srcA2 = "partial class C { int this[int x] { get => 1; init { } }}"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").SetMethod) }), DocumentResults(), }); } [Fact] public void AutoIndexer_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int this[int x] { get; set; } }"; var srcA2 = "partial class C { int this[int x] { get; set; } }"; var srcB2 = "partial class C { }"; // Accessors need to be updated even though they do not have an explicit body. // There is still a sequence point generated for them whose location needs to be updated. EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").SetMethod), }), DocumentResults(), }); } [Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")] public void IndexerWithExpressionBody_Partial_InsertDeleteUpdate_LiftedParameter() { var srcA1 = @" partial class C { }"; var srcB1 = @" partial class C { int this[int a] => new System.Func<int>(() => a + 1); }"; var srcA2 = @" partial class C { int this[int a] => new System.Func<int>(() => 2); // no capture }"; var srcB2 = @" partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a") }), DocumentResults(), }); } [Fact] public void AutoIndexer_ReadOnly_Add() { var src1 = @" struct S { int this[int x] { get; } }"; var src2 = @" struct S { readonly int this[int x] { get; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int this[int x]", CSharpFeaturesResources.indexer_getter)); } [Fact] public void Indexer_InMutableStruct_ReadOnly_Add() { var src1 = @" struct S { int this[int x] { get => 1; } int this[uint x] { get => 1; set {}} int this[byte x] { get => 1; set {}} int this[sbyte x] { get => 1; set {}} }"; var src2 = @" struct S { readonly int this[int x] { get => 1; } int this[uint x] { readonly get => 1; set {}} int this[byte x] { get => 1; readonly set {}} readonly int this[sbyte x] { get => 1; set {}} }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int this[int x]", CSharpFeaturesResources.indexer_getter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int this[sbyte x]", CSharpFeaturesResources.indexer_getter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int this[sbyte x]", CSharpFeaturesResources.indexer_setter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly get", CSharpFeaturesResources.indexer_getter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly set", CSharpFeaturesResources.indexer_setter)); } [Fact] public void Indexer_InReadOnlyStruct_ReadOnly_Add() { // indent to align accessor bodies and avoid updates caused by sequence point location changes var src1 = @" readonly struct S { int this[int x] { get => 1; } int this[uint x] { get => 1; set {}} int this[byte x] { get => 1; set {}} int this[sbyte x] { get => 1; set {}} }"; var src2 = @" readonly struct S { readonly int this[int x] { get => 1; } int this[uint x] { readonly get => 1; set {}} int this[byte x] { get => 1; readonly set {}} readonly int this[sbyte x] { get => 1; set {}} }"; var edits = GetTopEdits(src1, src2); // updates only for accessors whose modifiers were explicitly updated edits.VerifySemantics(new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.Parameters.Single().Type.Name == "UInt32").GetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.Parameters.Single().Type.Name == "Byte").SetMethod, preserveLocalVariables: false) }); } #endregion #region Events [Theory] [InlineData("static")] [InlineData("virtual")] [InlineData("abstract")] [InlineData("override")] [InlineData("sealed override", "override")] public void Event_Modifiers_Update(string oldModifiers, string newModifiers = "") { if (oldModifiers != "") { oldModifiers += " "; } if (newModifiers != "") { newModifiers += " "; } var src1 = "class C { " + oldModifiers + "event Action F { add {} remove {} } }"; var src2 = "class C { " + newModifiers + "event Action F { add {} remove {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [" + oldModifiers + "event Action F { add {} remove {} }]@10 -> [" + newModifiers + "event Action F { add {} remove {} }]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, newModifiers + "event Action F", FeaturesResources.event_)); } [Fact] public void EventAccessorReorder1() { var src1 = "class C { event int E { add { } remove { } } }"; var src2 = "class C { event int E { remove { } add { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [remove { }]@32 -> @24"); edits.VerifyRudeDiagnostics(); } [Fact] public void EventAccessorReorder2() { var src1 = "class C { event int E1 { add { } remove { } } event int E1 { add { } remove { } } }"; var src2 = "class C { event int E2 { remove { } add { } } event int E2 { remove { } add { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [event int E1 { add { } remove { } }]@10 -> [event int E2 { remove { } add { } }]@10", "Update [event int E1 { add { } remove { } }]@49 -> [event int E2 { remove { } add { } }]@49", "Reorder [remove { }]@33 -> @25", "Reorder [remove { }]@72 -> @64"); } [Fact] public void EventAccessorReorder3() { var src1 = "class C { event int E1 { add { } remove { } } event int E2 { add { } remove { } } }"; var src2 = "class C { event int E2 { remove { } add { } } event int E1 { remove { } add { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [event int E2 { add { } remove { } }]@49 -> @10", "Reorder [remove { }]@72 -> @25", "Reorder [remove { }]@33 -> @64"); } [Fact] public void EventInsert() { var src1 = "class C { }"; var src2 = "class C { event int E { remove { } add { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").GetMember("E"))); } [Fact] public void EventDelete() { var src1 = "class C { event int E { remove { } add { } } }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.event_, "E"))); } [Fact] public void EventInsert_IntoLayoutClass_Sequential() { var src1 = @" using System; using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Sequential)] class C { } "; var src2 = @" using System; using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Sequential)] class C { private event Action c { add { } remove { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Event_ExpressionBodyToBlockBody() { var src1 = @" using System; public class C { event Action E { add => F(); remove => F(); } } "; var src2 = @" using System; public class C { event Action E { add { F(); } remove { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [add => F();]@57 -> [add { F(); }]@56", "Update [remove => F();]@69 -> [remove { }]@69" ); edits.VerifySemanticDiagnostics(); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Event_BlockBodyToExpressionBody() { var src1 = @" using System; public class C { event Action E { add { F(); } remove { } } } "; var src2 = @" using System; public class C { event Action E { add => F(); remove => F(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [add { F(); }]@56 -> [add => F();]@57", "Update [remove { }]@69 -> [remove => F();]@69" ); edits.VerifySemanticDiagnostics(); } [Fact] public void Event_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { event int E { add { } remove { } } }"; var srcA2 = "partial class C { event int E { add { } remove { } } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E").AddMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E").RemoveMethod) }), DocumentResults(), }); } [Fact] public void Event_InMutableStruct_ReadOnly_Add() { var src1 = @" struct S { public event Action E { add {} remove {} } }"; var src2 = @" struct S { public readonly event Action E { add {} remove {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public readonly event Action E", FeaturesResources.event_)); } [Fact] public void Event_InReadOnlyStruct_ReadOnly_Add1() { var src1 = @" readonly struct S { public event Action E { add {} remove {} } }"; var src2 = @" readonly struct S { public readonly event Action E { add {} remove {} } }"; var edits = GetTopEdits(src1, src2); // Currently, an edit is produced eventhough bodies nor IsReadOnly attribute have changed. Consider improving. edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember<IEventSymbol>("E").AddMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember<IEventSymbol>("E").RemoveMethod)); } #endregion #region Parameter [Fact] public void ParameterRename_Method1() { var src1 = @"class C { public void M(int a) {} }"; var src2 = @"class C { public void M(int b) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@24 -> [int b]@24"); } [Fact] public void ParameterRename_Ctor1() { var src1 = @"class C { public C(int a) {} }"; var src2 = @"class C { public C(int b) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@19 -> [int b]@19"); } [Fact] public void ParameterRename_Operator1() { var src1 = @"class C { public static implicit operator int(C a) {} }"; var src2 = @"class C { public static implicit operator int(C b) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [C a]@46 -> [C b]@46"); } [Fact] public void ParameterRename_Operator2() { var src1 = @"class C { public static int operator +(C a, C b) { return 0; } }"; var src2 = @"class C { public static int operator +(C a, C x) { return 0; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [C b]@44 -> [C x]@44"); } [Fact] public void ParameterRename_Indexer2() { var src1 = @"class C { public int this[int a, int b] { get { return 0; } } }"; var src2 = @"class C { public int this[int a, int x] { get { return 0; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int b]@33 -> [int x]@33"); } [Fact] public void ParameterInsert1() { var src1 = @"class C { public void M() {} }"; var src2 = @"class C { public void M(int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [int a]@24"); } [Fact] public void ParameterInsert2() { var src1 = @"class C { public void M(int a) {} }"; var src2 = @"class C { public void M(int a, ref int b) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int a)]@23 -> [(int a, ref int b)]@23", "Insert [ref int b]@31"); } [Fact] public void ParameterDelete1() { var src1 = @"class C { public void M(int a) {} }"; var src2 = @"class C { public void M() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [int a]@24"); } [Fact] public void ParameterDelete2() { var src1 = @"class C { public void M(int a, int b) {} }"; var src2 = @"class C { public void M(int b) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int a, int b)]@23 -> [(int b)]@23", "Delete [int a]@24"); } [Fact] public void ParameterUpdate() { var src1 = @"class C { public void M(int a) {} }"; var src2 = @"class C { public void M(int b) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@24 -> [int b]@24"); } [Fact] public void ParameterReorder() { var src1 = @"class C { public void M(int a, int b) {} }"; var src2 = @"class C { public void M(int b, int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [int b]@31 -> @24"); } [Fact] public void ParameterReorderAndUpdate() { var src1 = @"class C { public void M(int a, int b) {} }"; var src2 = @"class C { public void M(int b, int c) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [int b]@31 -> @24", "Update [int a]@24 -> [int c]@31"); } [Theory] [InlineData("string", "string?")] [InlineData("object", "dynamic")] [InlineData("(int a, int b)", "(int a, int c)")] public void Parameter_Type_Update_RuntimeTypeUnchanged(string oldType, string newType) { var src1 = "class C { static void M(" + oldType + " a) {} }"; var src2 = "class C { static void M(" + newType + " a) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M"))); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void Parameter_Type_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C { static void M(" + oldType + " a) {} }"; var src2 = "class C { static void M(" + newType + " a) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, newType + " a", FeaturesResources.parameter)); } [Fact] public void Parameter_Type_Nullable() { var src1 = @" #nullable enable class C { static void M(string a) { } } "; var src2 = @" #nullable disable class C { static void M(string a) { } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Theory] [InlineData("this")] [InlineData("ref")] [InlineData("out")] [InlineData("params")] public void Parameter_Modifier_Remove(string modifier) { var src1 = @"static class C { static void F(" + modifier + " int[] a) { } }"; var src2 = @"static class C { static void F(int[] a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "int[] a", FeaturesResources.parameter)); } [Theory] [InlineData("int a = 1", "int a = 2")] [InlineData("int a = 1", "int a")] [InlineData("int a", "int a = 2")] [InlineData("object a = null", "object a")] [InlineData("object a", "object a = null")] [InlineData("double a = double.NaN", "double a = 1.2")] public void Parameter_Initializer_Update(string oldParameter, string newParameter) { var src1 = @"static class C { static void F(" + oldParameter + ") { } }"; var src2 = @"static class C { static void F(" + newParameter + ") { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, newParameter, FeaturesResources.parameter)); } [Fact] public void Parameter_Initializer_NaN() { var src1 = @"static class C { static void F(double a = System.Double.NaN) { } }"; var src2 = @"static class C { static void F(double a = double.NaN) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Parameter_Initializer_InsertDeleteUpdate() { var srcA1 = @"partial class C { }"; var srcB1 = @"partial class C { public static void F(int x = 1) {} }"; var srcA2 = @"partial class C { public static void F(int x = 2) {} }"; var srcB2 = @"partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.InitializerUpdate, "int x = 2", FeaturesResources.parameter) }), DocumentResults(), }); } [Fact] public void Parameter_Attribute_Insert() { var attribute = "public class A : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M(int a) {} }"; var src2 = attribute + @"class C { public void M([A]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@63 -> [[A]int a]@63"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Parameter_Attribute_Insert_SupportedByRuntime_NonCustomAttribute() { var src1 = @"class C { public void M(int a) {} }"; var src2 = @"class C { public void M([System.Runtime.InteropServices.InAttribute]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@24 -> [[System.Runtime.InteropServices.InAttribute]int a]@24"); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities, Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Insert_SupportedByRuntime_SecurityAttribute1() { var attribute = "public class AAttribute : System.Security.Permissions.SecurityAttribute { }\n\n"; var src1 = attribute + @"class C { public void M(int a) {} }"; var src2 = attribute + @"class C { public void M([A]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@101 -> [[A]int a]@101"); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities, Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Insert_SupportedByRuntime_SecurityAttribute2() { var attribute = "public class BAttribute : System.Security.Permissions.SecurityAttribute { }\n\n" + "public class AAttribute : BAttribute { }\n\n"; var src1 = attribute + @"class C { public void M(int a) {} }"; var src2 = attribute + @"class C { public void M([A]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@143 -> [[A]int a]@143"); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities, Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Insert_NotSupportedByRuntime1() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M(int a) {} }"; var src2 = attribute + @"class C { public void M([A]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@72 -> [[A]int a]@72"); edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Insert_NotSupportedByRuntime2() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M([A]int a) {} }"; var src2 = attribute + @"class C { public void M([A, B]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]int a]@120 -> [[A, B]int a]@120"); edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Delete_NotSupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M([A]int a) {} }"; var src2 = attribute + @"class C { public void M(int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]int a]@72 -> [int a]@72"); edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Update_NotSupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M([System.Obsolete(""1""), B]int a) {} }"; var src2 = attribute + @"class C { public void M([System.Obsolete(""2""), A]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete(\"1\"), B]int a]@120 -> [[System.Obsolete(\"2\"), A]int a]@120"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Update() { var attribute = "class A : System.Attribute { public A(int x) {} } "; var src1 = attribute + "class C { void F([A(0)]int a) {} }"; var src2 = attribute + "class C { void F([A(1)]int a) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A(0)]int a]@67 -> [[A(1)]int a]@67"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Parameter_Attribute_Update_WithBodyUpdate() { var attribute = "class A : System.Attribute { public A(int x) {} } "; var src1 = attribute + "class C { void F([A(0)]int a) { F(0); } }"; var src2 = attribute + "class C { void F([A(1)]int a) { F(1); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void F([A(0)]int a) { F(0); }]@60 -> [void F([A(1)]int a) { F(1); }]@60", "Update [[A(0)]int a]@67 -> [[A(1)]int a]@67"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } #endregion #region Method Type Parameter [Fact] public void MethodTypeParameterInsert1() { var src1 = @"class C { public void M() {} }"; var src2 = @"class C { public void M<A>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [<A>]@23", "Insert [A]@24"); } [Fact] public void MethodTypeParameterInsert2() { var src1 = @"class C { public void M<A>() {} }"; var src2 = @"class C { public void M<A,B>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [<A>]@23 -> [<A,B>]@23", "Insert [B]@26"); } [Fact] public void MethodTypeParameterDelete1() { var src1 = @"class C { public void M<A>() {} }"; var src2 = @"class C { public void M() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [<A>]@23", "Delete [A]@24"); } [Fact] public void MethodTypeParameterDelete2() { var src1 = @"class C { public void M<A,B>() {} }"; var src2 = @"class C { public void M<B>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [<A,B>]@23 -> [<B>]@23", "Delete [A]@24"); } [Fact] public void MethodTypeParameterUpdate() { var src1 = @"class C { public void M<A>() {} }"; var src2 = @"class C { public void M<B>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [A]@24 -> [B]@24"); } [Fact] public void MethodTypeParameterReorder() { var src1 = @"class C { public void M<A,B>() {} }"; var src2 = @"class C { public void M<B,A>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [B]@26 -> @24"); } [Fact] public void MethodTypeParameterReorderAndUpdate() { var src1 = @"class C { public void M<A,B>() {} }"; var src2 = @"class C { public void M<B,C>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [B]@26 -> @24", "Update [A]@24 -> [C]@26"); } [Fact] public void MethodTypeParameter_Attribute_Insert1() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M<T>() {} }"; var src2 = attribute + @"class C { public void M<[A]T>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [T]@72 -> [[A]T]@72"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericMethodUpdate, "T"), Diagnostic(RudeEditKind.GenericMethodTriviaUpdate, "", FeaturesResources.method)); } [Fact] public void MethodTypeParameter_Attribute_Insert2() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M<[A]T>() {} }"; var src2 = attribute + @"class C { public void M<[A, B]T>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]T]@120 -> [[A, B]T]@120"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericMethodUpdate, "T"), Diagnostic(RudeEditKind.GenericMethodTriviaUpdate, "", FeaturesResources.method)); } [Fact] public void MethodTypeParameter_Attribute_Delete() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M<[A]T>() {} }"; var src2 = attribute + @"class C { public void M<T>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]T]@72 -> [T]@72"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericMethodTriviaUpdate, "", FeaturesResources.method), Diagnostic(RudeEditKind.GenericMethodUpdate, "T")); } [Fact] public void MethodTypeParameter_Attribute_Update_NotSupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M<[System.Obsolete(""1""), B]T>() {} }"; var src2 = attribute + @"class C { public void M<[System.Obsolete(""2""), A]T>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete(\"1\"), B]T]@120 -> [[System.Obsolete(\"2\"), A]T]@120"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericMethodUpdate, "T")); } [Fact] public void MethodTypeParameter_Attribute_Update() { var attribute = "class A : System.Attribute { public A(int x) {} } "; var src1 = attribute + "class C { void F<[A(0)]T>(T a) {} }"; var src2 = attribute + "class C { void F<[A(1)]T>(T a) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A(0)]T]@67 -> [[A(1)]T]@67"); edits.VerifyRudeDiagnostics( EditAndContinueTestHelpers.Net6RuntimeCapabilities, Diagnostic(RudeEditKind.GenericMethodUpdate, "T")); } [Fact] public void MethodTypeParameter_Attribute_Update_WithBodyUpdate() { var attribute = "class A : System.Attribute { public A(int x) {} } "; var src1 = attribute + "class C { void F<[A(0)]T>(T a) { F(0); } }"; var src2 = attribute + "class C { void F<[A(1)]T>(T a) { F(1); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void F<[A(0)]T>(T a) { F(0); }]@60 -> [void F<[A(1)]T>(T a) { F(1); }]@60", "Update [[A(0)]T]@67 -> [[A(1)]T]@67"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.GenericMethodUpdate, "void F<[A(1)]T>(T a)"), Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericMethodUpdate, "T")); } #endregion #region Type Type Parameter [Fact] public void TypeTypeParameterInsert1() { var src1 = @"class C {}"; var src2 = @"class C<A> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [<A>]@7", "Insert [A]@8"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "A", FeaturesResources.type_parameter)); } [Fact] public void TypeTypeParameterInsert2() { var src1 = @"class C<A> {}"; var src2 = @"class C<A,B> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [<A>]@7 -> [<A,B>]@7", "Insert [B]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "B", FeaturesResources.type_parameter)); } [Fact] public void TypeTypeParameterDelete1() { var src1 = @"class C<A> { }"; var src2 = @"class C { } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [<A>]@7", "Delete [A]@8"); } [Fact] public void TypeTypeParameterDelete2() { var src1 = @"class C<A,B> {}"; var src2 = @"class C<B> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [<A,B>]@7 -> [<B>]@7", "Delete [A]@8"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "class C<B>", DeletedSymbolDisplay(FeaturesResources.type_parameter, "A"))); } [Fact] public void TypeTypeParameterUpdate() { var src1 = @"class C<A> {}"; var src2 = @"class C<B> {} "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [A]@8 -> [B]@8"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "B", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "B")); } [Fact] public void TypeTypeParameterReorder() { var src1 = @"class C<A,B> { }"; var src2 = @"class C<B,A> { } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [B]@10 -> @8"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "B", FeaturesResources.type_parameter)); } [Fact] public void TypeTypeParameterReorderAndUpdate() { var src1 = @"class C<A,B> {}"; var src2 = @"class C<B,C> {} "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [B]@10 -> @8", "Update [A]@8 -> [C]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "B", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.Renamed, "C", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "C")); } [Fact] public void TypeTypeParameterAttributeInsert1() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C<T> {}"; var src2 = attribute + @"class C<[A]T> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [T]@56 -> [[A]T]@56"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void TypeTypeParameterAttributeInsert2() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C<[A]T> {}"; var src2 = attribute + @"class C<[A, B]T> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]T]@104 -> [[A, B]T]@104"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void TypeTypeParameterAttributeInsert_SupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C<T> {}"; var src2 = attribute + @"class C<[A]T> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [T]@56 -> [[A]T]@56"); edits.VerifyRudeDiagnostics( EditAndContinueTestHelpers.Net6RuntimeCapabilities, Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void TypeTypeParameterAttributeDelete() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C<[A]T> {}"; var src2 = attribute + @"class C<T> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]T]@56 -> [T]@56"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void TypeTypeParameterAttributeUpdate() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C<[System.Obsolete(""1""), B]T> {}"; var src2 = attribute + @"class C<[System.Obsolete(""2""), A]T> {} "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete(\"1\"), B]T]@104 -> [[System.Obsolete(\"2\"), A]T]@104"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void TypeTypeParameter_Partial_Attribute_AddMultiple() { var attributes = @" class A : System.Attribute {} class B : System.Attribute {} "; var srcA1 = "partial class C<T> { }" + attributes; var srcB1 = "partial class C<T> { }"; var srcA2 = "partial class C<[A]T> { }" + attributes; var srcB2 = "partial class C<[B]T> { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "T"), }), DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "T"), }), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void TypeTypeParameter_Partial_Attribute_AddMultiple_Reloadable() { var attributes = @" class A : System.Attribute {} class B : System.Attribute {} "; var srcA1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C<T> { }" + attributes; var srcB1 = "partial class C<T> { }"; var srcA2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C<[A]T> { }" + attributes; var srcB2 = "partial class C<[B]T> { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C") }), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C") }), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } #endregion #region Type Parameter Constraints [Theory] [InlineData("nonnull")] [InlineData("struct")] [InlineData("class")] [InlineData("new()")] [InlineData("unmanaged")] [InlineData("System.IDisposable")] [InlineData("System.Delegate")] public void TypeConstraint_Insert(string newConstraint) { var src1 = "class C<S,T> { }"; var src2 = "class C<S,T> where T : " + newConstraint + " { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [where T : " + newConstraint + "]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingConstraints, "where T : " + newConstraint, FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "where T : " + newConstraint)); } [Theory] [InlineData("nonnull")] [InlineData("struct")] [InlineData("class")] [InlineData("new()")] [InlineData("unmanaged")] [InlineData("System.IDisposable")] [InlineData("System.Delegate")] public void TypeConstraint_Delete(string oldConstraint) { var src1 = "class C<S,T> where T : " + oldConstraint + " { }"; var src2 = "class C<S,T> { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [where T : " + oldConstraint + "]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingConstraints, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Theory] [InlineData("string", "string?")] [InlineData("(int a, int b)", "(int a, int c)")] public void TypeConstraint_Update_RuntimeTypeUnchanged(string oldType, string newType) { // note: dynamic is not allowed in constraints var src1 = "class C<T> where T : System.Collections.Generic.List<" + oldType + "> {}"; var src2 = "class C<T> where T : System.Collections.Generic.List<" + newType + "> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.GenericTypeUpdate, "where T : System.Collections.Generic.List<" + newType + ">")); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void TypeConstraint_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C<T> where T : System.Collections.Generic.List<" + oldType + "> {}"; var src2 = "class C<T> where T : System.Collections.Generic.List<" + newType + "> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingConstraints, "where T : System.Collections.Generic.List<" + newType + ">", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "where T : System.Collections.Generic.List<" + newType + ">")); } [Fact] public void TypeConstraint_Delete_WithParameter() { var src1 = "class C<S,T> where S : new() where T : class { }"; var src2 = "class C<S> where S : new() { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "class C<S>", DeletedSymbolDisplay(FeaturesResources.type_parameter, "T"))); } [Fact] public void TypeConstraint_MultipleClauses_Insert() { var src1 = "class C<S,T> where T : class { }"; var src2 = "class C<S,T> where S : unmanaged where T : class { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [where S : unmanaged]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingConstraints, "where S : unmanaged", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "where S : unmanaged")); } [Fact] public void TypeConstraint_MultipleClauses_Delete() { var src1 = "class C<S,T> where S : new() where T : class { }"; var src2 = "class C<S,T> where T : class { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [where S : new()]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingConstraints, "S", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "S")); } [Fact] public void TypeConstraint_MultipleClauses_Reorder() { var src1 = "class C<S,T> where S : struct where T : class { }"; var src2 = "class C<S,T> where T : class where S : struct { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [where T : class]@30 -> @13"); edits.VerifyRudeDiagnostics(); } [Fact] public void TypeConstraint_MultipleClauses_UpdateAndReorder() { var src1 = "class C<S,T> where S : new() where T : class { }"; var src2 = "class C<T,S> where T : class, I where S : class, new() { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [where T : class]@29 -> @13", "Reorder [T]@10 -> @8", "Update [where T : class]@29 -> [where T : class, I]@13", "Update [where S : new()]@13 -> [where S : class, new()]@32"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.ChangingConstraints, "where T : class, I", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "where T : class, I"), Diagnostic(RudeEditKind.ChangingConstraints, "where S : class, new()", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "where S : class, new()")); } #endregion #region Top Level Statements [Fact] public void TopLevelStatements_Update() { var src1 = @" using System; Console.WriteLine(""Hello""); "; var src2 = @" using System; Console.WriteLine(""Hello World""); "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [Console.WriteLine(\"Hello\");]@19 -> [Console.WriteLine(\"Hello World\");]@19"); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("<Program>$.<Main>$"))); } [Fact] public void TopLevelStatements_InsertAndUpdate() { var src1 = @" using System; Console.WriteLine(""Hello""); "; var src2 = @" using System; Console.WriteLine(""Hello World""); Console.WriteLine(""What is your name?""); var name = Console.ReadLine(); "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Console.WriteLine(\"Hello\");]@19 -> [Console.WriteLine(\"Hello World\");]@19", "Insert [Console.WriteLine(\"What is your name?\");]@54", "Insert [var name = Console.ReadLine();]@96"); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("<Program>$.<Main>$"))); } [Fact] public void TopLevelStatements_Insert_NoImplicitMain() { var src1 = @" using System; "; var src2 = @" using System; Console.WriteLine(""Hello World""); "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [Console.WriteLine(\"Hello World\");]@19"); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("<Program>$.<Main>$"))); } [Fact] public void TopLevelStatements_Insert_ImplicitMain() { var src1 = @" using System; Console.WriteLine(""Hello""); "; var src2 = @" using System; Console.WriteLine(""Hello""); Console.WriteLine(""World""); "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [Console.WriteLine(\"World\");]@48"); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("<Program>$.<Main>$"))); } [Fact] public void TopLevelStatements_Delete_NoImplicitMain() { var src1 = @" using System; Console.WriteLine(""Hello World""); "; var src2 = @" using System; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [Console.WriteLine(\"Hello World\");]@19"); edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.Delete, null, CSharpFeaturesResources.global_statement)); } [Fact] public void TopLevelStatements_Delete_ImplicitMain() { var src1 = @" using System; Console.WriteLine(""Hello""); Console.WriteLine(""World""); "; var src2 = @" using System; Console.WriteLine(""Hello""); "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [Console.WriteLine(\"World\");]@48"); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("<Program>$.<Main>$"))); } [Fact] public void TopLevelStatements_StackAlloc() { var src1 = @"unsafe { var x = stackalloc int[3]; System.Console.Write(1); }"; var src2 = @"unsafe { var x = stackalloc int[3]; System.Console.Write(2); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", CSharpFeaturesResources.global_statement)); } [Fact] public void TopLevelStatements_VoidToInt1() { var src1 = @" using System; Console.Write(1); "; var src2 = @" using System; Console.Write(1); return 1; "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return 1;")); } [Fact] public void TopLevelStatements_VoidToInt2() { var src1 = @" using System; Console.Write(1); return; "; var src2 = @" using System; Console.Write(1); return 1; "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return 1;")); } [Fact] public void TopLevelStatements_VoidToInt3() { var src1 = @" using System; Console.Write(1); int Goo() { return 1; } "; var src2 = @" using System; Console.Write(1); return 1; int Goo() { return 1; } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return 1;")); } [Fact] public void TopLevelStatements_AddAwait() { var src1 = @" using System.Threading.Tasks; await Task.Delay(100); "; var src2 = @" using System.Threading.Tasks; await Task.Delay(100); await Task.Delay(200); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "await", CSharpFeaturesResources.await_expression)); } [Fact] public void TopLevelStatements_DeleteAwait() { var src1 = @" using System.Threading.Tasks; await Task.Delay(100); await Task.Delay(200); "; var src2 = @" using System.Threading.Tasks; await Task.Delay(100); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, null, CSharpFeaturesResources.await_expression)); } [Fact] public void TopLevelStatements_VoidToTask() { var src1 = @" using System; using System.Threading.Tasks; Console.Write(1); "; var src2 = @" using System; using System.Threading.Tasks; await Task.Delay(100); Console.Write(1); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "await Task.Delay(100);")); } [Fact] public void TopLevelStatements_TaskToTaskInt() { var src1 = @" using System; using System.Threading.Tasks; await Task.Delay(100); Console.Write(1); "; var src2 = @" using System; using System.Threading.Tasks; await Task.Delay(100); Console.Write(1); return 1; "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return 1;")); } [Fact] public void TopLevelStatements_VoidToTaskInt() { var src1 = @" using System; using System.Threading.Tasks; Console.Write(1); "; var src2 = @" using System; using System.Threading.Tasks; Console.Write(1); return await GetInt(); Task<int> GetInt() { return Task.FromResult(1); } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return await GetInt();")); } [Fact] public void TopLevelStatements_IntToVoid1() { var src1 = @" using System; Console.Write(1); return 1; "; var src2 = @" using System; Console.Write(1); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "Console.Write(1);")); } [Fact] public void TopLevelStatements_IntToVoid2() { var src1 = @" using System; Console.Write(1); return 1; "; var src2 = @" using System; Console.Write(1); return; "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return;")); } [Fact] public void TopLevelStatements_IntToVoid3() { var src1 = @" using System; Console.Write(1); return 1; int Goo() { return 1; } "; var src2 = @" using System; Console.Write(1); int Goo() { return 1; } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "int Goo()\r\n{\r\n return 1;\r\n}")); } [Fact] public void TopLevelStatements_IntToVoid4() { var src1 = @" using System; Console.Write(1); return 1; public class C { public int Goo() { return 1; } } "; var src2 = @" using System; Console.Write(1); public class C { public int Goo() { return 1; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "Console.Write(1);")); } [Fact] public void TopLevelStatements_TaskToVoid() { var src1 = @" using System; using System.Threading.Tasks; await Task.Delay(100); Console.Write(1); "; var src2 = @" using System; using System.Threading.Tasks; Console.Write(1); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "Console.Write(1);"), Diagnostic(RudeEditKind.Delete, null, CSharpFeaturesResources.await_expression)); } [Fact] public void TopLevelStatements_TaskIntToTask() { var src1 = @" using System; using System.Threading.Tasks; await Task.Delay(100); Console.Write(1); return 1; "; var src2 = @" using System; using System.Threading.Tasks; await Task.Delay(100); Console.Write(1); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "Console.Write(1);")); } [Fact] public void TopLevelStatements_TaskIntToVoid() { var src1 = @" using System; using System.Threading.Tasks; Console.Write(1); return await GetInt(); Task<int> GetInt() { return Task.FromResult(1); } "; var src2 = @" using System; using System.Threading.Tasks; Console.Write(1); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "Console.Write(1);"), Diagnostic(RudeEditKind.Delete, null, CSharpFeaturesResources.await_expression)); } [Fact] public void TopLevelStatements_WithLambda_Insert() { var src1 = @" using System; Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; "; var src2 = @" using System; Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; Console.WriteLine(1); "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("<Program>$.<Main>$"), syntaxMap[0]) }); } [Fact] public void TopLevelStatements_WithLambda_Update() { var src1 = @" using System; Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; Console.WriteLine(1); public class C { } "; var src2 = @" using System; Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; Console.WriteLine(2); public class C { } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("<Program>$.<Main>$"), syntaxMap[0]) }); } [Fact] public void TopLevelStatements_WithLambda_Delete() { var src1 = @" using System; Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; Console.WriteLine(1); public class C { } "; var src2 = @" using System; Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; public class C { } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("<Program>$.<Main>$"), syntaxMap[0]) }); } [Fact] public void TopLevelStatements_UpdateMultiple() { var src1 = @" using System; Console.WriteLine(1); Console.WriteLine(2); public class C { } "; var src2 = @" using System; Console.WriteLine(3); Console.WriteLine(4); public class C { } "; var edits = GetTopEdits(src1, src2); // Since each individual statement is a separate update to a separate node, this just validates we correctly // only analyze the things once edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("<Program>$.<Main>$"))); } [Fact] public void TopLevelStatements_MoveToOtherFile() { var srcA1 = @" using System; Console.WriteLine(1); public class A { }"; var srcB1 = @" using System; public class B { }"; var srcA2 = @" using System; public class A { }"; var srcB2 = @" using System; Console.WriteLine(2); public class B { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new [] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("<Program>$.<Main>$")) }), }); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.EditAndContinue.UnitTests; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { [UseExportProvider] public class TopLevelEditingTests : EditingTestBase { #region Usings [Fact] public void Using_Global_Insert() { var src1 = @" using System.Collections.Generic; "; var src2 = @" global using D = System.Diagnostics; global using System.Collections; using System.Collections.Generic; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [global using D = System.Diagnostics;]@2", "Insert [global using System.Collections;]@40"); edits.VerifyRudeDiagnostics(); } [Fact] public void Using_Delete1() { var src1 = @" using System.Diagnostics; "; var src2 = @""; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [using System.Diagnostics;]@2"); Assert.IsType<UsingDirectiveSyntax>(edits.Edits.First().OldNode); Assert.Null(edits.Edits.First().NewNode); } [Fact] public void Using_Delete2() { var src1 = @" using D = System.Diagnostics; using System.Collections; using System.Collections.Generic; "; var src2 = @" using System.Collections.Generic; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [using D = System.Diagnostics;]@2", "Delete [using System.Collections;]@33"); edits.VerifyRudeDiagnostics(); } [Fact] public void Using_Insert() { var src1 = @" using System.Collections.Generic; "; var src2 = @" using D = System.Diagnostics; using System.Collections; using System.Collections.Generic; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [using D = System.Diagnostics;]@2", "Insert [using System.Collections;]@33"); edits.VerifyRudeDiagnostics(); } [Fact] public void Using_Update1() { var src1 = @" using System.Diagnostics; using System.Collections; using System.Collections.Generic; "; var src2 = @" using System.Diagnostics; using X = System.Collections; using System.Collections.Generic; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [using System.Collections;]@29 -> [using X = System.Collections;]@29"); edits.VerifyRudeDiagnostics(); } [Fact] public void Using_Update2() { var src1 = @" using System.Diagnostics; using X1 = System.Collections; using System.Collections.Generic; "; var src2 = @" using System.Diagnostics; using X2 = System.Collections; using System.Collections.Generic; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [using X1 = System.Collections;]@29 -> [using X2 = System.Collections;]@29"); edits.VerifyRudeDiagnostics(); } [Fact] public void Using_Update3() { var src1 = @" using System.Diagnostics; using System.Collections; using System.Collections.Generic; "; var src2 = @" using System; using System.Collections; using System.Collections.Generic; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [using System.Diagnostics;]@2 -> [using System;]@2"); edits.VerifyRudeDiagnostics(); } [Fact] public void Using_Reorder1() { var src1 = @" using System.Diagnostics; using System.Collections; using System.Collections.Generic; "; var src2 = @" using System.Collections; using System.Collections.Generic; using System.Diagnostics; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [using System.Diagnostics;]@2 -> @64"); } [Fact] public void Using_InsertDelete1() { var src1 = @" namespace N { using System.Collections; } namespace M { } "; var src2 = @" namespace N { } namespace M { using System.Collections; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [using System.Collections;]@43", "Delete [using System.Collections;]@22"); } [Fact] public void Using_InsertDelete2() { var src1 = @" namespace N { using System.Collections; } "; var src2 = @" using System.Collections; namespace N { } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [using System.Collections;]@2", "Delete [using System.Collections;]@22"); } [Fact] public void Using_Delete_ChangesCodeMeaning() { // This test specifically validates the scenario we _don't_ support, namely when inserting or deleting // a using directive, if existing code changes in meaning as a result, we don't issue edits for that code. // If this ever regresses then please buy a lottery ticket because the feature has magically fixed itself. var src1 = @" using System.IO; using DirectoryInfo = N.C; namespace N { public class C { public C(string a) { } public FileAttributes Attributes { get; set; } } public class D { public void M() { var d = new DirectoryInfo(""aa""); var x = directoryInfo.Attributes; } } }"; var src2 = @" using System.IO; namespace N { public class C { public C(string a) { } public FileAttributes Attributes { get; set; } } public class D { public void M() { var d = new DirectoryInfo(""aa""); var x = directoryInfo.Attributes; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [using DirectoryInfo = N.C;]@20"); edits.VerifySemantics(); } [Fact] public void Using_Insert_ForNewCode() { // As distinct from the above, this test validates a real world scenario of inserting a using directive // and changing code that utilizes the new directive to some effect. var src1 = @" namespace N { class Program { static void Main(string[] args) { } } }"; var src2 = @" using System; namespace N { class Program { static void Main(string[] args) { Console.WriteLine(""Hello World!""); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("N.Program.Main"))); } [Fact] public void Using_Delete_ForOldCode() { var src1 = @" using System; namespace N { class Program { static void Main(string[] args) { Console.WriteLine(""Hello World!""); } } }"; var src2 = @" namespace N { class Program { static void Main(string[] args) { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("N.Program.Main"))); } [Fact] public void Using_Insert_CreatesAmbiguousCode() { // This test validates that we still issue edits for changed valid code, even when unchanged // code has ambiguities after adding a using. var src1 = @" using System.Threading; namespace N { class C { void M() { // Timer exists in System.Threading and System.Timers var t = new Timer(s => System.Console.WriteLine(s)); } } }"; var src2 = @" using System.Threading; using System.Timers; namespace N { class C { void M() { // Timer exists in System.Threading and System.Timers var t = new Timer(s => System.Console.WriteLine(s)); } void M2() { // TimersDescriptionAttribute only exists in System.Timers System.Console.WriteLine(new TimersDescriptionAttribute("""")); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("N.C.M2"))); } #endregion #region Extern Alias [Fact] public void ExternAliasUpdate() { var src1 = "extern alias X;"; var src2 = "extern alias Y;"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [extern alias X;]@0 -> [extern alias Y;]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Update, "extern alias Y;", CSharpFeaturesResources.extern_alias)); } [Fact] public void ExternAliasInsert() { var src1 = ""; var src2 = "extern alias Y;"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [extern alias Y;]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "extern alias Y;", CSharpFeaturesResources.extern_alias)); } [Fact] public void ExternAliasDelete() { var src1 = "extern alias Y;"; var src2 = ""; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [extern alias Y;]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, null, CSharpFeaturesResources.extern_alias)); } #endregion #region Assembly/Module Attributes [Fact] public void Insert_TopLevelAttribute() { var src1 = ""; var src2 = "[assembly: System.Obsolete(\"2\")]"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [[assembly: System.Obsolete(\"2\")]]@0", "Insert [System.Obsolete(\"2\")]@11"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "[assembly: System.Obsolete(\"2\")]", FeaturesResources.attribute)); } [Fact] public void Delete_TopLevelAttribute() { var src1 = "[assembly: System.Obsolete(\"2\")]"; var src2 = ""; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [[assembly: System.Obsolete(\"2\")]]@0", "Delete [System.Obsolete(\"2\")]@11"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, null, FeaturesResources.attribute)); } [Fact] public void Update_TopLevelAttribute() { var src1 = "[assembly: System.Obsolete(\"1\")]"; var src2 = "[assembly: System.Obsolete(\"2\")]"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[assembly: System.Obsolete(\"1\")]]@0 -> [[assembly: System.Obsolete(\"2\")]]@0", "Update [System.Obsolete(\"1\")]@11 -> [System.Obsolete(\"2\")]@11"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Update, "System.Obsolete(\"2\")", FeaturesResources.attribute)); } [Fact] public void Reorder_TopLevelAttribute() { var src1 = "[assembly: System.Obsolete(\"1\")][assembly: System.Obsolete(\"2\")]"; var src2 = "[assembly: System.Obsolete(\"2\")][assembly: System.Obsolete(\"1\")]"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [[assembly: System.Obsolete(\"2\")]]@32 -> @0"); edits.VerifyRudeDiagnostics(); } #endregion #region Types [Theory] [InlineData("class", "struct")] [InlineData("class", "record")] // TODO: Allow this conversion: https://github.com/dotnet/roslyn/issues/51874 [InlineData("class", "record struct")] [InlineData("class", "interface")] [InlineData("struct", "record struct")] // TODO: Allow this conversion: https://github.com/dotnet/roslyn/issues/51874 public void Type_Kind_Update(string oldKeyword, string newKeyword) { var src1 = oldKeyword + " C { }"; var src2 = newKeyword + " C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [" + oldKeyword + " C { }]@0 -> [" + newKeyword + " C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeKindUpdate, newKeyword + " C")); } [Theory] [InlineData("class", "struct")] [InlineData("class", "record")] [InlineData("class", "record struct")] [InlineData("class", "interface")] [InlineData("struct", "record struct")] public void Type_Kind_Update_Reloadable(string oldKeyword, string newKeyword) { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]" + oldKeyword + " C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]" + newKeyword + " C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[CreateNewOnMetadataUpdate]" + oldKeyword + " C { }]@145 -> [[CreateNewOnMetadataUpdate]" + newKeyword + " C { }]@145"); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Type_Modifiers_Static_Remove() { var src1 = "public static class C { }"; var src2 = "public class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public static class C { }]@0 -> [public class C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public class C", FeaturesResources.class_)); } [Theory] [InlineData("public")] [InlineData("protected")] [InlineData("private")] [InlineData("private protected")] [InlineData("internal protected")] public void Type_Modifiers_Accessibility_Change(string accessibility) { var src1 = accessibility + " class C { }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [" + accessibility + " class C { }]@0 -> [class C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "class C", FeaturesResources.class_)); } [Theory] [InlineData("public", "public")] [InlineData("internal", "internal")] [InlineData("", "internal")] [InlineData("internal", "")] [InlineData("protected", "protected")] [InlineData("private", "private")] [InlineData("private protected", "private protected")] [InlineData("internal protected", "internal protected")] public void Type_Modifiers_Accessibility_Partial(string accessibilityA, string accessibilityB) { var srcA1 = accessibilityA + " partial class C { }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = accessibilityB + " partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(), }); } [Fact] public void Type_Modifiers_Internal_Remove() { var src1 = "internal interface C { }"; var src2 = "interface C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Fact] public void Type_Modifiers_Internal_Add() { var src1 = "struct C { }"; var src2 = "internal struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Fact] public void Type_Modifiers_Accessibility_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]public class C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]internal class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[CreateNewOnMetadataUpdate]public class C { }]@145 -> [[CreateNewOnMetadataUpdate]internal class C { }]@145"); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Theory] [InlineData("class")] [InlineData("struct")] [InlineData("interface")] [InlineData("record")] [InlineData("record struct")] public void Type_Modifiers_NestedPrivateInInterface_Remove(string keyword) { var src1 = "interface C { private " + keyword + " S { } }"; var src2 = "interface C { " + keyword + " S { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, keyword + " S", GetResource(keyword))); } [Theory] [InlineData("class")] [InlineData("struct")] [InlineData("interface")] [InlineData("record")] [InlineData("record struct")] public void Type_Modifiers_NestedPrivateInClass_Add(string keyword) { var src1 = "class C { " + keyword + " S { } }"; var src2 = "class C { private " + keyword + " S { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Theory] [InlineData("class")] [InlineData("struct")] [InlineData("interface")] [InlineData("record")] [InlineData("record struct")] public void Type_Modifiers_NestedPublicInInterface_Add(string keyword) { var src1 = "interface C { " + keyword + " S { } }"; var src2 = "interface C { public " + keyword + " S { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Fact, WorkItem(48628, "https://github.com/dotnet/roslyn/issues/48628")] public void Type_Modifiers_Unsafe_Add() { var src1 = "public class C { }"; var src2 = "public unsafe class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public class C { }]@0 -> [public unsafe class C { }]@0"); edits.VerifyRudeDiagnostics(); } [Fact, WorkItem(48628, "https://github.com/dotnet/roslyn/issues/48628")] public void Type_Modifiers_Unsafe_Remove() { var src1 = @" using System; unsafe delegate void D(); class C { unsafe class N { } public unsafe event Action<int> A { add { } remove { } } unsafe int F() => 0; unsafe int X; unsafe int Y { get; } unsafe C() {} unsafe ~C() {} } "; var src2 = @" using System; delegate void D(); class C { class N { } public event Action<int> A { add { } remove { } } int F() => 0; int X; int Y { get; } C() {} ~C() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [unsafe delegate void D();]@17 -> [delegate void D();]@17", "Update [unsafe class N { }]@60 -> [class N { }]@53", "Update [public unsafe event Action<int> A { add { } remove { } }]@84 -> [public event Action<int> A { add { } remove { } }]@70", "Update [unsafe int F() => 0;]@146 -> [int F() => 0;]@125", "Update [unsafe int X;]@172 -> [int X;]@144", "Update [unsafe int Y { get; }]@191 -> [int Y { get; }]@156", "Update [unsafe C() {}]@218 -> [C() {}]@176", "Update [unsafe ~C() {}]@237 -> [~C() {}]@188"); edits.VerifyRudeDiagnostics(); } [Fact, WorkItem(48628, "https://github.com/dotnet/roslyn/issues/48628")] public void Type_Modifiers_Unsafe_DeleteInsert() { var srcA1 = "partial class C { unsafe void F() { } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { void F() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F")) }), }); } [Fact] public void Type_Modifiers_Ref_Add() { var src1 = "public struct C { }"; var src2 = "public ref struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public struct C { }]@0 -> [public ref struct C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public ref struct C", CSharpFeaturesResources.struct_)); } [Fact] public void Type_Modifiers_Ref_Remove() { var src1 = "public ref struct C { }"; var src2 = "public struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public ref struct C { }]@0 -> [public struct C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public struct C", CSharpFeaturesResources.struct_)); } [Fact] public void Type_Modifiers_ReadOnly_Add() { var src1 = "public struct C { }"; var src2 = "public readonly struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public struct C { }]@0 -> [public readonly struct C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public readonly struct C", CSharpFeaturesResources.struct_)); } [Fact] public void Type_Modifiers_ReadOnly_Remove() { var src1 = "public readonly struct C { }"; var src2 = "public struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public readonly struct C { }]@0 -> [public struct C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public struct C", CSharpFeaturesResources.struct_)); } [Fact] public void Type_Attribute_Update_NotSupportedByRuntime1() { var attribute = "public class A1Attribute : System.Attribute { }\n\n" + "public class A2Attribute : System.Attribute { }\n\n"; var src1 = attribute + "[A1]class C { }"; var src2 = attribute + "[A2]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A1]class C { }]@98 -> [[A2]class C { }]@98"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Fact] public void Type_Attribute_Update_NotSupportedByRuntime2() { var src1 = "[System.Obsolete(\"1\")]class C { }"; var src2 = "[System.Obsolete(\"2\")]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete(\"1\")]class C { }]@0 -> [[System.Obsolete(\"2\")]class C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Fact] public void Type_Attribute_Delete_NotSupportedByRuntime1() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + "[A, B]class C { }"; var src2 = attribute + "[A]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A, B]class C { }]@96 -> [[A]class C { }]@96"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Fact] public void Type_Attribute_Delete_NotSupportedByRuntime2() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + "[B, A]class C { }"; var src2 = attribute + "[A]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[B, A]class C { }]@96 -> [[A]class C { }]@96"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Fact] public void Type_Attribute_Change_Reloadable() { var attributeSrc = @" public class A1 : System.Attribute { } public class A2 : System.Attribute { } public class A3 : System.Attribute { } "; var src1 = ReloadableAttributeSrc + attributeSrc + "[CreateNewOnMetadataUpdate, A1, A2]class C { }"; var src2 = ReloadableAttributeSrc + attributeSrc + "[CreateNewOnMetadataUpdate, A2, A3]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[CreateNewOnMetadataUpdate, A1, A2]class C { }]@267 -> [[CreateNewOnMetadataUpdate, A2, A3]class C { }]@267"); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Type_Attribute_ReloadableRemove() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var src2 = ReloadableAttributeSrc + "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Type_Attribute_ReloadableAdd() { var src1 = ReloadableAttributeSrc + "class C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Type_Attribute_ReloadableBase() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class B { } class C : B { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class B { } class C : B { void F() {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Type_Attribute_Add() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + "[A]class C { }"; var src2 = attribute + "[A, B]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]class C { }]@96 -> [[A, B]class C { }]@96"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Type_Attribute_Add_NotSupportedByRuntime1() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + "[A]class C { }"; var src2 = attribute + "[A, B]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]class C { }]@96 -> [[A, B]class C { }]@96"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Fact] public void Type_Attribute_Add_NotSupportedByRuntime2() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "class C { }"; var src2 = attribute + "[A]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [class C { }]@48 -> [[A]class C { }]@48"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Fact] public void Type_Attribute_Reorder1() { var src1 = "[A(1), B(2), C(3)]class C { }"; var src2 = "[C(3), A(1), B(2)]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A(1), B(2), C(3)]class C { }]@0 -> [[C(3), A(1), B(2)]class C { }]@0"); edits.VerifyRudeDiagnostics(); } [Fact] public void Type_Attribute_Reorder2() { var src1 = "[A, B, C]class C { }"; var src2 = "[B, C, A]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A, B, C]class C { }]@0 -> [[B, C, A]class C { }]@0"); edits.VerifyRudeDiagnostics(); } [Fact] public void Type_Attribute_ReorderAndUpdate_NotSupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + "[System.Obsolete(\"1\"), A, B]class C { }"; var src2 = attribute + "[A, B, System.Obsolete(\"2\")]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete(\"1\"), A, B]class C { }]@96 -> [[A, B, System.Obsolete(\"2\")]class C { }]@96"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Theory] [InlineData("class")] [InlineData("struct")] [InlineData("interface")] [InlineData("record")] [InlineData("record struct")] public void Type_Rename(string keyword) { var src1 = keyword + " C { }"; var src2 = keyword + " D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [" + keyword + " C { }]@0 -> [" + keyword + " D { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, keyword + " D", GetResource(keyword))); } [Fact] public void Type_Rename_AddAndDeleteMember() { var src1 = "class C { int x = 1; }"; var src2 = "class D { void F() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [class C { int x = 1; }]@0 -> [class D { void F() { } }]@0", "Insert [void F() { }]@10", "Insert [()]@16", "Delete [int x = 1;]@10", "Delete [int x = 1]@10", "Delete [x = 1]@14"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "class D", FeaturesResources.class_)); } [Fact] [WorkItem(54886, "https://github.com/dotnet/roslyn/issues/54886")] public void Type_Rename_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[CreateNewOnMetadataUpdate]class C { }]@145 -> [[CreateNewOnMetadataUpdate]class D { }]@145"); // TODO: expected: Replace edit of D edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Renamed, "class D", FeaturesResources.class_)); } [Fact] [WorkItem(54886, "https://github.com/dotnet/roslyn/issues/54886")] public void Type_Rename_Reloadable_AddAndDeleteMember() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { int x = 1; }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class D { void F() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[CreateNewOnMetadataUpdate]class C { int x = 1; }]@145 -> [[CreateNewOnMetadataUpdate]class D { void F() { } }]@145", "Insert [void F() { }]@182", "Insert [()]@188", "Delete [int x = 1;]@182", "Delete [int x = 1]@182", "Delete [x = 1]@186"); // TODO: expected: Replace edit of D edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Renamed, "class D", FeaturesResources.class_)); } [Fact] public void Interface_NoModifiers_Insert() { var src1 = ""; var src2 = "interface C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Interface_NoModifiers_IntoNamespace_Insert() { var src1 = "namespace N { } "; var src2 = "namespace N { interface C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Interface_NoModifiers_IntoType_Insert() { var src1 = "interface N { }"; var src2 = "interface N { interface C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Class_NoModifiers_Insert() { var src1 = ""; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Class_NoModifiers_IntoNamespace_Insert() { var src1 = "namespace N { }"; var src2 = "namespace N { class C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Class_NoModifiers_IntoType_Insert() { var src1 = "struct N { }"; var src2 = "struct N { class C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Struct_NoModifiers_Insert() { var src1 = ""; var src2 = "struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Struct_NoModifiers_IntoNamespace_Insert() { var src1 = "namespace N { }"; var src2 = "namespace N { struct C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Struct_NoModifiers_IntoType_Insert() { var src1 = "struct N { }"; var src2 = "struct N { struct C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Type_BaseType_Add_Unchanged() { var src1 = "class C { }"; var src2 = "class C : object { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [class C { }]@0 -> [class C : object { }]@0"); edits.VerifySemantics(); } [Fact] public void Type_BaseType_Add_Changed() { var src1 = "class C { }"; var src2 = "class C : D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [class C { }]@0 -> [class C : D { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class C", FeaturesResources.class_)); } [Theory] [InlineData("string", "string?")] [InlineData("string[]", "string[]?")] [InlineData("object", "dynamic")] [InlineData("dynamic?", "dynamic")] [InlineData("(int a, int b)", "(int a, int c)")] public void Type_BaseType_Update_RuntimeTypeUnchanged(string oldType, string newType) { var src1 = "class C : System.Collections.Generic.List<" + oldType + "> {}"; var src2 = "class C : System.Collections.Generic.List<" + newType + "> {}"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C"))); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void Type_BaseType_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C : System.Collections.Generic.List<" + oldType + "> {}"; var src2 = "class C : System.Collections.Generic.List<" + newType + "> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class C", FeaturesResources.class_)); } [Fact] public void Type_BaseType_Update_CompileTimeTypeUnchanged() { var src1 = "using A = System.Int32; using B = System.Int32; class C : System.Collections.Generic.List<A> {}"; var src2 = "using A = System.Int32; using B = System.Int32; class C : System.Collections.Generic.List<B> {}"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Fact] public void Type_BaseInterface_Add() { var src1 = "class C { }"; var src2 = "class C : IDisposable { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [class C { }]@0 -> [class C : IDisposable { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class C", FeaturesResources.class_)); } [Fact] public void Type_BaseInterface_Delete_Inherited() { var src1 = @" interface B {} interface A : B {} class C : A, B {} "; var src2 = @" interface B {} interface A : B {} class C : A {} "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Fact] public void Type_BaseInterface_Reorder() { var src1 = "class C : IGoo, IBar { }"; var src2 = "class C : IBar, IGoo { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [class C : IGoo, IBar { }]@0 -> [class C : IBar, IGoo { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class C", FeaturesResources.class_)); } [Theory] [InlineData("string", "string?")] [InlineData("object", "dynamic")] [InlineData("(int a, int b)", "(int a, int c)")] public void Type_BaseInterface_Update_RuntimeTypeUnchanged(string oldType, string newType) { var src1 = "class C : System.Collections.Generic.IEnumerable<" + oldType + "> {}"; var src2 = "class C : System.Collections.Generic.IEnumerable<" + newType + "> {}"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C"))); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void Type_BaseInterface_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C : System.Collections.Generic.IEnumerable<" + oldType + "> {}"; var src2 = "class C : System.Collections.Generic.IEnumerable<" + newType + "> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class C", FeaturesResources.class_)); } [Fact] public void Type_Base_Partial() { var srcA1 = "partial class C : B, I { }"; var srcB1 = "partial class C : J { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C : B, I, J { }"; var srcC = @" class B {} interface I {} interface J {}"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC, srcC) }, new[] { DocumentResults(), DocumentResults(), DocumentResults() }); } [Fact] public void Type_Base_Partial_InsertDeleteAndUpdate() { var srcA1 = "partial class C { }"; var srcB1 = ""; var srcC1 = "partial class C { }"; var srcA2 = ""; var srcB2 = "partial class C : D { }"; var srcC2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "partial class C", FeaturesResources.class_) }), DocumentResults(), }); } [Fact] public void Type_Base_InsertDelete() { var srcA1 = ""; var srcB1 = "class C : B, I { }"; var srcA2 = "class C : B, I { }"; var srcB2 = ""; var srcC = @" class B {} interface I {} interface J {}"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC, srcC) }, new[] { DocumentResults(), DocumentResults(), DocumentResults() }); } [Fact] public void Type_Reloadable_NotSupportedByRuntime() { var src1 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] public class C { void F() { System.Console.WriteLine(1); } }"; var src2 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] public class C { void F() { System.Console.WriteLine(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.ChangingReloadableTypeNotSupportedByRuntime, "void F()", "CreateNewOnMetadataUpdateAttribute")); } [Fact] public void Type_Insert_AbstractVirtualOverride() { var src1 = ""; var src2 = @" public abstract class C<T> { public abstract void F(); public virtual void G() {} public override string ToString() => null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Type_Insert_NotSupportedByRuntime() { var src1 = @" public class C { void F() { } }"; var src2 = @" public class C { void F() { } } public class D { void M() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "public class D", FeaturesResources.class_)); } [Fact] public void Type_Insert_Reloadable() { var src1 = ReloadableAttributeSrc + ""; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { void F() {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C"))); } [Fact] public void InterfaceInsert() { var src1 = ""; var src2 = @" public interface I { void F(); static void G() {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void RefStructInsert() { var src1 = ""; var src2 = "ref struct X { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [ref struct X { }]@0"); edits.VerifyRudeDiagnostics(); } [Fact] public void Struct_ReadOnly_Insert() { var src1 = ""; var src2 = "readonly struct X { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [readonly struct X { }]@0"); edits.VerifyRudeDiagnostics(); } [Fact] public void Struct_RefModifier_Add() { var src1 = "struct X { }"; var src2 = "ref struct X { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [struct X { }]@0 -> [ref struct X { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "ref struct X", CSharpFeaturesResources.struct_)); } [Fact] public void Struct_ReadonlyModifier_Add() { var src1 = "struct X { }"; var src2 = "readonly struct X { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [struct X { }]@0 -> [readonly struct X { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "readonly struct X", SyntaxFacts.GetText(SyntaxKind.StructKeyword))); } [Theory] [InlineData("ref")] [InlineData("readonly")] public void Struct_Modifiers_Partial_InsertDelete(string modifier) { var srcA1 = modifier + " partial struct S { }"; var srcB1 = "partial struct S { }"; var srcA2 = "partial struct S { }"; var srcB2 = modifier + " partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults() }); } [Fact] public void Class_ImplementingInterface_Add() { var src1 = @" using System; public interface ISample { string Get(); } public interface IConflict { string Get(); } public class BaseClass : ISample { public virtual string Get() => string.Empty; } "; var src2 = @" using System; public interface ISample { string Get(); } public interface IConflict { string Get(); } public class BaseClass : ISample { public virtual string Get() => string.Empty; } public class SubClass : BaseClass, IConflict { public override string Get() => string.Empty; string IConflict.Get() => String.Empty; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Insert [public class SubClass : BaseClass, IConflict { public override string Get() => string.Empty; string IConflict.Get() => String.Empty; }]@219", "Insert [public override string Get() => string.Empty;]@272", "Insert [string IConflict.Get() => String.Empty;]@325", "Insert [()]@298", "Insert [()]@345"); // Here we add a class implementing an interface and a method inside it with explicit interface specifier. // We want to be sure that adding the method will not tirgger a rude edit as it happens if adding a single method with explicit interface specifier. edits.VerifyRudeDiagnostics(); } [WorkItem(37128, "https://github.com/dotnet/roslyn/issues/37128")] [Fact] public void Interface_InsertMembers() { var src1 = @" using System; interface I { } "; var src2 = @" using System; interface I { static int StaticField = 10; static void StaticMethod() { } void VirtualMethod1() { } virtual void VirtualMethod2() { } abstract void AbstractMethod(); sealed void NonVirtualMethod() { } public static int operator +(I a, I b) => 1; static int StaticProperty1 { get => 1; set { } } static int StaticProperty2 => 1; virtual int VirtualProperty1 { get => 1; set { } } virtual int VirtualProperty2 { get => 1; } int VirtualProperty3 { get => 1; set { } } int VirtualProperty4 { get => 1; } abstract int AbstractProperty1 { get; set; } abstract int AbstractProperty2 { get; } sealed int NonVirtualProperty => 1; int this[byte virtualIndexer] => 1; int this[sbyte virtualIndexer] { get => 1; } virtual int this[ushort virtualIndexer] { get => 1; set {} } virtual int this[short virtualIndexer] { get => 1; set {} } abstract int this[uint abstractIndexer] { get; set; } abstract int this[int abstractIndexer] { get; } sealed int this[ulong nonVirtualIndexer] { get => 1; set {} } sealed int this[long nonVirtualIndexer] { get => 1; set {} } static event Action StaticEvent; static event Action StaticEvent2 { add { } remove { } } event Action VirtualEvent { add { } remove { } } abstract event Action AbstractEvent; sealed event Action NonVirtualEvent { add { } remove { } } abstract class C { } interface J { } enum E { } delegate void D(); } "; var edits = GetTopEdits(src1, src2); // TODO: InsertIntoInterface errors are reported due to https://github.com/dotnet/roslyn/issues/37128. edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoInterface, "static void StaticMethod()", FeaturesResources.method), Diagnostic(RudeEditKind.InsertVirtual, "void VirtualMethod1()", FeaturesResources.method), Diagnostic(RudeEditKind.InsertVirtual, "virtual void VirtualMethod2()", FeaturesResources.method), Diagnostic(RudeEditKind.InsertVirtual, "abstract void AbstractMethod()", FeaturesResources.method), Diagnostic(RudeEditKind.InsertIntoInterface, "sealed void NonVirtualMethod()", FeaturesResources.method), Diagnostic(RudeEditKind.InsertOperator, "public static int operator +(I a, I b)", FeaturesResources.operator_), Diagnostic(RudeEditKind.InsertIntoInterface, "static int StaticProperty1", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertIntoInterface, "static int StaticProperty2", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertIntoInterface, "static int StaticProperty2", CSharpFeaturesResources.property_getter), Diagnostic(RudeEditKind.InsertVirtual, "virtual int VirtualProperty1", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertVirtual, "virtual int VirtualProperty2", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertVirtual, "int VirtualProperty3", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertVirtual, "int VirtualProperty4", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertVirtual, "abstract int AbstractProperty1", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertVirtual, "abstract int AbstractProperty2", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertIntoInterface, "sealed int NonVirtualProperty", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertIntoInterface, "sealed int NonVirtualProperty", CSharpFeaturesResources.property_getter), Diagnostic(RudeEditKind.InsertVirtual, "int this[byte virtualIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertVirtual, "int this[byte virtualIndexer]", CSharpFeaturesResources.indexer_getter), Diagnostic(RudeEditKind.InsertVirtual, "int this[sbyte virtualIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertVirtual, "virtual int this[ushort virtualIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertVirtual, "virtual int this[short virtualIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertVirtual, "abstract int this[uint abstractIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertVirtual, "abstract int this[int abstractIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertIntoInterface, "sealed int this[ulong nonVirtualIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertIntoInterface, "sealed int this[long nonVirtualIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertIntoInterface, "static event Action StaticEvent2", FeaturesResources.event_), Diagnostic(RudeEditKind.InsertVirtual, "event Action VirtualEvent", FeaturesResources.event_), Diagnostic(RudeEditKind.InsertIntoInterface, "sealed event Action NonVirtualEvent", FeaturesResources.event_), Diagnostic(RudeEditKind.InsertIntoInterface, "StaticField = 10", FeaturesResources.field), Diagnostic(RudeEditKind.InsertIntoInterface, "StaticEvent", CSharpFeaturesResources.event_field), Diagnostic(RudeEditKind.InsertVirtual, "AbstractEvent", CSharpFeaturesResources.event_field)); } [Fact] public void Interface_InsertDelete() { var srcA1 = @" interface I { static void M() { } } "; var srcB1 = @" "; var srcA2 = @" "; var srcB2 = @" interface I { static void M() { } } "; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("M")) }), }); } [Fact] public void Type_Generic_InsertMembers() { var src1 = @" using System; class C<T> { } "; var src2 = @" using System; class C<T> { void M() {} int P1 { get; set; } int P2 { get => 1; set {} } int this[int i] { get => 1; set {} } event Action E { add {} remove {} } event Action EF; int F1, F2; enum E {} interface I {} class D {} } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoGenericType, "void M()", FeaturesResources.method), Diagnostic(RudeEditKind.InsertIntoGenericType, "int P1", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertIntoGenericType, "int P2", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertIntoGenericType, "int this[int i]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertIntoGenericType, "event Action E", FeaturesResources.event_), Diagnostic(RudeEditKind.InsertIntoGenericType, "EF", CSharpFeaturesResources.event_field), Diagnostic(RudeEditKind.InsertIntoGenericType, "F1", FeaturesResources.field), Diagnostic(RudeEditKind.InsertIntoGenericType, "F2", FeaturesResources.field)); } [Fact] public void Type_Generic_InsertMembers_Reloadable() { var src1 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] class C<T> { } "; var src2 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] class C<T> { void M() {} int P1 { get; set; } int P2 { get => 1; set {} } int this[int i] { get => 1; set {} } event System.Action E { add {} remove {} } event System.Action EF; int F1, F2; enum E {} interface I {} class D {} } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Type_Generic_DeleteInsert() { var srcA1 = @" class C<T> { void F() {} } struct S<T> { void F() {} } interface I<T> { void F() {} } "; var srcB1 = ""; var srcA2 = srcB1; var srcB2 = srcA1; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "class C<T>"), Diagnostic(RudeEditKind.GenericTypeUpdate, "struct S<T>"), Diagnostic(RudeEditKind.GenericTypeUpdate, "interface I<T>"), Diagnostic(RudeEditKind.GenericTypeUpdate, "void F()"), Diagnostic(RudeEditKind.GenericTypeUpdate, "void F()"), Diagnostic(RudeEditKind.GenericTypeUpdate, "void F()"), Diagnostic(RudeEditKind.GenericTypeUpdate, "T"), Diagnostic(RudeEditKind.GenericTypeUpdate, "T"), Diagnostic(RudeEditKind.GenericTypeUpdate, "T"), }) }); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/54881")] [WorkItem(54881, "https://github.com/dotnet/roslyn/issues/54881")] public void Type_TypeParameter_Insert_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]public class C<T> { void F() { } }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]internal class C<T, S> { int x = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Type_Delete() { var src1 = @" class C { void F() {} } struct S { void F() {} } interface I { void F() {} } "; var src2 = ""; GetTopEdits(src1, src2).VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.class_, "C")), Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(CSharpFeaturesResources.struct_, "S")), Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.interface_, "I"))); } [Fact] public void Type_Delete_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { void F() {} }"; var src2 = ReloadableAttributeSrc; GetTopEdits(src1, src2).VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.class_, "C"))); } [Fact] public void Type_Partial_DeleteDeclaration() { var srcA1 = "partial class C { void F() {} void M() { } }"; var srcB1 = "partial class C { void G() {} }"; var srcA2 = ""; var srcB2 = "partial class C { void G() {} void M() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.method, "C.F()")) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("M")), }) }); } [Fact] public void Type_Partial_InsertFirstDeclaration() { var src1 = ""; var src2 = "partial class C { void F() {} }"; GetTopEdits(src1, src2).VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C"), preserveLocalVariables: false) }); } [Fact] public void Type_Partial_InsertSecondDeclaration() { var srcA1 = "partial class C { void F() {} }"; var srcB1 = ""; var srcA2 = "partial class C { void F() {} }"; var srcB2 = "partial class C { void G() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").GetMember("G"), preserveLocalVariables: false) }), }); } [Fact] public void Type_Partial_Reloadable() { var srcA1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { void F() {} }"; var srcB1 = ""; var srcA2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { void F() {} }"; var srcB2 = "partial class C { void G() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C") }), }); } [Fact] public void Type_DeleteInsert() { var srcA1 = @" class C { void F() {} } struct S { void F() {} } interface I { void F() {} } "; var srcB1 = ""; var srcA2 = srcB1; var srcB2 = srcA1; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember("F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("F")), }) }); } [Fact] public void Type_DeleteInsert_Reloadable() { var srcA1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { void F() {} }"; var srcB1 = ""; var srcA2 = ReloadableAttributeSrc; var srcB2 = "[CreateNewOnMetadataUpdate]class C { void F() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C")), }) }); } [Fact] public void Type_NonInsertableMembers_DeleteInsert() { var srcA1 = @" abstract class C { public abstract void AbstractMethod(); public virtual void VirtualMethod() {} public override string ToString() => null; public void I.G() {} } interface I { void G(); void F() {} } "; var srcB1 = ""; var srcA2 = srcB1; var srcB2 = srcA1; // TODO: The methods without bodies do not need to be updated. EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("AbstractMethod")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("VirtualMethod")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("ToString")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("I.G")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("G")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("F")), }) }); } [Fact] public void Type_Attribute_NonInsertableMembers_DeleteInsert() { var srcA1 = @" abstract class C { public abstract void AbstractMethod(); public virtual void VirtualMethod() {} public override string ToString() => null; public void I.G() {} } interface I { void G(); void F() {} } "; var srcB1 = ""; var srcA2 = ""; var srcB2 = @" abstract class C { [System.Obsolete]public abstract void AbstractMethod(); public virtual void VirtualMethod() {} public override string ToString() => null; public void I.G() {} } interface I { [System.Obsolete]void G(); void F() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("AbstractMethod")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("VirtualMethod")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("ToString")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("I.G")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("G")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("F")), }) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Type_DeleteInsert_DataMembers() { var srcA1 = @" class C { public int x = 1; public int y = 2; public int P { get; set; } = 3; public event System.Action E = new System.Action(null); } "; var srcB1 = ""; var srcA2 = ""; var srcB2 = @" class C { public int x = 1; public int y = 2; public int P { get; set; } = 3; public event System.Action E = new System.Action(null); } "; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true), }) }); } [Fact] public void Type_DeleteInsert_DataMembers_PartialSplit() { var srcA1 = @" class C { public int x = 1; public int y = 2; public int P { get; set; } = 3; } "; var srcB1 = ""; var srcA2 = @" partial class C { public int x = 1; public int y = 2; } "; var srcB2 = @" partial class C { public int P { get; set; } = 3; } "; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true), }) }); } [Fact] public void Type_DeleteInsert_DataMembers_PartialMerge() { var srcA1 = @" partial class C { public int x = 1; public int y = 2; } "; var srcB1 = @" partial class C { public int P { get; set; } = 3; }"; var srcA2 = @" class C { public int x = 1; public int y = 2; public int P { get; set; } = 3; } "; var srcB2 = @" "; // note that accessors are not updated since they do not have bodies EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true), }), DocumentResults() }); } #endregion #region Records [Fact] public void Record_Partial_MovePrimaryConstructor() { var src1 = @" partial record C { } partial record C(int X);"; var src2 = @" partial record C(int X); partial record C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_Name_Update() { var src1 = "record C { }"; var src2 = "record D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [record C { }]@0 -> [record D { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "record D", CSharpFeaturesResources.record_)); } [Fact] public void RecordStruct_NoModifiers_Insert() { var src1 = ""; var src2 = "record struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void RecordStruct_AddField() { var src1 = @" record struct C(int X) { }"; var src2 = @" record struct C(int X) { private int _y = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoStruct, "_y = 0", FeaturesResources.field, CSharpFeaturesResources.record_struct)); } [Fact] public void RecordStruct_AddProperty() { var src1 = @" record struct C(int X) { }"; var src2 = @" record struct C(int X) { public int Y { get; set; } = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoStruct, "public int Y { get; set; } = 0;", FeaturesResources.auto_property, CSharpFeaturesResources.record_struct)); } [Fact] public void Record_NoModifiers_Insert() { var src1 = ""; var src2 = "record C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_NoModifiers_IntoNamespace_Insert() { var src1 = "namespace N { }"; var src2 = "namespace N { record C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_NoModifiers_IntoType_Insert() { var src1 = "struct N { }"; var src2 = "struct N { record C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_BaseTypeUpdate1() { var src1 = "record C { }"; var src2 = "record C : D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [record C { }]@0 -> [record C : D { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "record C", CSharpFeaturesResources.record_)); } [Fact] public void Record_BaseTypeUpdate2() { var src1 = "record C : D1 { }"; var src2 = "record C : D2 { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [record C : D1 { }]@0 -> [record C : D2 { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "record C", CSharpFeaturesResources.record_)); } [Fact] public void Record_BaseInterfaceUpdate1() { var src1 = "record C { }"; var src2 = "record C : IDisposable { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [record C { }]@0 -> [record C : IDisposable { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "record C", CSharpFeaturesResources.record_)); } [Fact] public void Record_BaseInterfaceUpdate2() { var src1 = "record C : IGoo, IBar { }"; var src2 = "record C : IGoo { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [record C : IGoo, IBar { }]@0 -> [record C : IGoo { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "record C", CSharpFeaturesResources.record_)); } [Fact] public void Record_BaseInterfaceUpdate3() { var src1 = "record C : IGoo, IBar { }"; var src2 = "record C : IBar, IGoo { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [record C : IGoo, IBar { }]@0 -> [record C : IBar, IGoo { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "record C", CSharpFeaturesResources.record_)); } [Fact] public void RecordInsert_AbstractVirtualOverride() { var src1 = ""; var src2 = @" public abstract record C<T> { public abstract void F(); public virtual void G() {} public override void H() {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_PrintMembers() { var src1 = "record C { }"; var src2 = @" record C { protected virtual bool PrintMembers(System.Text.StringBuilder builder) { return true; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers"))); edits.VerifyRudeDiagnostics(); } [Fact] public void RecordStruct_ImplementSynthesized_PrintMembers() { var src1 = "record struct C { }"; var src2 = @" record struct C { private bool PrintMembers(System.Text.StringBuilder builder) { return true; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_WrongParameterName() { // TODO: Remove this requirement with https://github.com/dotnet/roslyn/issues/52563 var src1 = "record C { }"; var src2 = @" record C { protected virtual bool PrintMembers(System.Text.StringBuilder sb) { return false; } public virtual bool Equals(C rhs) { return false; } protected C(C other) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ExplicitRecordMethodParameterNamesMustMatch, "protected virtual bool PrintMembers(System.Text.StringBuilder sb)", "PrintMembers(System.Text.StringBuilder builder)"), Diagnostic(RudeEditKind.ExplicitRecordMethodParameterNamesMustMatch, "public virtual bool Equals(C rhs)", "Equals(C other)"), Diagnostic(RudeEditKind.ExplicitRecordMethodParameterNamesMustMatch, "protected C(C other)", "C(C original)")); } [Fact] public void Record_ImplementSynthesized_ToString() { var src1 = "record C { }"; var src2 = @" record C { public override string ToString() { return ""R""; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.ToString"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_UnImplementSynthesized_ToString() { var src1 = @" record C { public override string ToString() { return ""R""; } }"; var src2 = "record C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.ToString"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddProperty_Primary() { var src1 = "record C(int X);"; var src2 = "record C(int X, int Y);"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "int Y", FeaturesResources.parameter)); } [Fact] public void Record_AddProperty_NotPrimary() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int Y { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.Y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddProperty_NotPrimary_WithConstructor() { var src1 = @" record C(int X) { public C(string fromAString) { } }"; var src2 = @" record C(int X) { public int Y { get; set; } public C(string fromAString) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.Y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddProperty_NotPrimary_WithExplicitMembers() { var src1 = @" record C(int X) { protected virtual bool PrintMembers(System.Text.StringBuilder builder) { return false; } public override int GetHashCode() { return 0; } public virtual bool Equals(C other) { return false; } public C(C original) { } }"; var src2 = @" record C(int X) { public int Y { get; set; } protected virtual bool PrintMembers(System.Text.StringBuilder builder) { return false; } public override int GetHashCode() { return 0; } public virtual bool Equals(C other) { return false; } public C(C original) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.Y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddProperty_NotPrimary_WithInitializer() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int Y { get; set; } = 1; }"; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.Y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddField() { var src1 = "record C(int X) { }"; var src2 = "record C(int X) { private int _y; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C._y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddField_WithExplicitMembers() { var src1 = @" record C(int X) { public C(C other) { } }"; var src2 = @" record C(int X) { private int _y; public C(C other) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C._y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddField_WithInitializer() { var src1 = "record C(int X) { }"; var src2 = "record C(int X) { private int _y = 1; }"; var syntaxMap = GetSyntaxMap(src1, src2); var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C._y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddField_WithExistingInitializer() { var src1 = "record C(int X) { private int _y = <N:0.0>1</N:0.0>; }"; var src2 = "record C(int X) { private int _y = <N:0.0>1</N:0.0>; private int _z; }"; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C._z")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), syntaxMap[0]), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddField_WithInitializerAndExistingInitializer() { var src1 = "record C(int X) { private int _y = <N:0.0>1</N:0.0>; }"; var src2 = "record C(int X) { private int _y = <N:0.0>1</N:0.0>; private int _z = 1; }"; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C._z")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), syntaxMap[0]), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_DeleteField() { var src1 = "record C(int X) { private int _y; }"; var src2 = "record C(int X) { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.Delete, "record C", DeletedSymbolDisplay(FeaturesResources.field, "_y"))); } [Fact] public void Record_DeleteProperty_Primary() { var src1 = "record C(int X, int Y) { }"; var src2 = "record C(int X) { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.Delete, "record C", DeletedSymbolDisplay(FeaturesResources.parameter, "int Y"))); } [Fact] public void Record_DeleteProperty_NotPrimary() { var src1 = "record C(int X) { public int P { get; set; } }"; var src2 = "record C(int X) { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "record C", DeletedSymbolDisplay(FeaturesResources.auto_property, "P"))); } [Fact] public void Record_ImplementSynthesized_Property() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int X { get; init; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_Property_WithBody() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int X { get { return 4; } init { throw null; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_Property_WithExpressionBody() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int X { get => 4; init => throw null; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_Property_InitToSet() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int X { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ImplementRecordParameterWithSet, "public int X", "X")); } [Fact] public void Record_ImplementSynthesized_Property_MakeReadOnly() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int X { get; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ImplementRecordParameterAsReadOnly, "public int X", "X")); } [Fact] public void Record_UnImplementSynthesized_Property() { var src1 = @" record C(int X) { public int X { get; init; } }"; var src2 = "record C(int X);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_UnImplementSynthesized_Property_WithExpressionBody() { var src1 = @" record C(int X) { public int X { get => 4; init => throw null; } }"; var src2 = "record C(int X);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_UnImplementSynthesized_Property_WithBody() { var src1 = @" record C(int X) { public int X { get { return 4; } init { } } }"; var src2 = "record C(int X);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_Property_Partial() { var srcA1 = @"partial record C(int X);"; var srcB1 = @"partial record C;"; var srcA2 = @"partial record C(int X);"; var srcB2 = @" partial record C { public int X { get; init; } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), partialType: "C", preserveLocalVariables: true) }) }); } [Fact] public void Record_UnImplementSynthesized_Property_Partial() { var srcA1 = @"partial record C(int X);"; var srcB1 = @" partial record C { public int X { get; init; } }"; var srcA2 = @"partial record C(int X);"; var srcB2 = @"partial record C;"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), partialType: "C", preserveLocalVariables: true) }) }); } [Fact] public void Record_ImplementSynthesized_Property_Partial_WithBody() { var srcA1 = @"partial record C(int X);"; var srcB1 = @"partial record C;"; var srcA2 = @"partial record C(int X);"; var srcB2 = @" partial record C { public int X { get { return 4; } init { throw null; } } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), partialType : "C", preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C")) }) }); } [Fact] public void Record_UnImplementSynthesized_Property_Partial_WithBody() { var srcA1 = @"partial record C(int X);"; var srcB1 = @" partial record C { public int X { get { return 4; } init { throw null; } } }"; var srcA2 = @"partial record C(int X);"; var srcB2 = @"partial record C;"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), partialType : "C", preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C")) }) }); } [Fact] public void Record_MoveProperty_Partial() { var srcA1 = @" partial record C(int X) { public int Y { get; init; } }"; var srcB1 = @" partial record C; "; var srcA2 = @" partial record C(int X); "; var srcB2 = @" partial record C { public int Y { get; init; } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.Y").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.Y").SetMethod) }), }); } [Fact] public void Record_UnImplementSynthesized_Property_WithInitializer() { var src1 = @" record C(int X) { public int X { get; init; } = 1; }"; var src2 = "record C(int X);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_UnImplementSynthesized_Property_WithInitializerMatchingCompilerGenerated() { var src1 = @" record C(int X) { public int X { get; init; } = X; }"; var src2 = "record C(int X);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_Property_Delete_NotPrimary() { var src1 = @" record C(int X) { public int Y { get; init; } }"; var src2 = "record C(int X);"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "record C", DeletedSymbolDisplay(FeaturesResources.auto_property, "Y"))); } [Fact] public void Record_PropertyInitializer_Update_NotPrimary() { var src1 = "record C { int X { get; } = 0; }"; var src2 = "record C { int X { get; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Length == 0), preserveLocalVariables: true)); } [Fact] public void Record_PropertyInitializer_Update_Primary() { var src1 = "record C(int X) { int X { get; } = 0; }"; var src2 = "record C(int X) { int X { get; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); } #endregion #region Enums [Fact] public void Enum_NoModifiers_Insert() { var src1 = ""; var src2 = "enum C { A }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Enum_NoModifiers_IntoNamespace_Insert() { var src1 = "namespace N { }"; var src2 = "namespace N { enum C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Enum_NoModifiers_IntoType_Insert() { var src1 = "struct N { }"; var src2 = "struct N { enum C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Enum_Attribute_Insert() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "enum E { }"; var src2 = attribute + "[A]enum E { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum E { }]@48 -> [[A]enum E { }]@48"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "enum E", FeaturesResources.enum_)); } [Fact] public void Enum_Member_Attribute_Delete() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "enum E { [A]X }"; var src2 = attribute + "enum E { X }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]X]@57 -> [X]@57"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "X", FeaturesResources.enum_value)); } [Fact] public void Enum_Member_Attribute_Insert() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "enum E { X }"; var src2 = attribute + "enum E { [A]X }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [X]@57 -> [[A]X]@57"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "[A]X", FeaturesResources.enum_value)); } [Fact] public void Enum_Member_Attribute_Update() { var attribute = "public class A1Attribute : System.Attribute { }\n\n" + "public class A2Attribute : System.Attribute { }\n\n"; var src1 = attribute + "enum E { [A1]X }"; var src2 = attribute + "enum E { [A2]X }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A1]X]@107 -> [[A2]X]@107"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "[A2]X", FeaturesResources.enum_value)); } [Fact] public void Enum_Member_Attribute_InsertDeleteAndUpdate() { var srcA1 = ""; var srcB1 = "enum N { A = 1 }"; var srcA2 = "enum N { [System.Obsolete]A = 1 }"; var srcB2 = ""; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("N.A")) }), DocumentResults() }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Enum_Rename() { var src1 = "enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Colors { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum Color { Red = 1, Blue = 2, }]@0 -> [enum Colors { Red = 1, Blue = 2, }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "enum Colors", FeaturesResources.enum_)); } [Fact] public void Enum_BaseType_Add() { var src1 = "enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Color : ushort { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color { Red = 1, Blue = 2, }]@0 -> [enum Color : ushort { Red = 1, Blue = 2, }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.EnumUnderlyingTypeUpdate, "enum Color", FeaturesResources.enum_)); } [Fact] public void Enum_BaseType_Add_Unchanged() { var src1 = "enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Color : int { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color { Red = 1, Blue = 2, }]@0 -> [enum Color : int { Red = 1, Blue = 2, }]@0"); edits.VerifySemantics(); } [Fact] public void Enum_BaseType_Update() { var src1 = "enum Color : ushort { Red = 1, Blue = 2, }"; var src2 = "enum Color : long { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color : ushort { Red = 1, Blue = 2, }]@0 -> [enum Color : long { Red = 1, Blue = 2, }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.EnumUnderlyingTypeUpdate, "enum Color", FeaturesResources.enum_)); } [Fact] public void Enum_BaseType_Delete_Unchanged() { var src1 = "enum Color : int { Red = 1, Blue = 2, }"; var src2 = "enum Color { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color : int { Red = 1, Blue = 2, }]@0 -> [enum Color { Red = 1, Blue = 2, }]@0"); edits.VerifySemantics(); } [Fact] public void Enum_BaseType_Delete_Changed() { var src1 = "enum Color : ushort { Red = 1, Blue = 2, }"; var src2 = "enum Color { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color : ushort { Red = 1, Blue = 2, }]@0 -> [enum Color { Red = 1, Blue = 2, }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.EnumUnderlyingTypeUpdate, "enum Color", FeaturesResources.enum_)); } [Fact] public void EnumAccessibilityChange() { var src1 = "public enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Color { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public enum Color { Red = 1, Blue = 2, }]@0 -> [enum Color { Red = 1, Blue = 2, }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "enum Color", FeaturesResources.enum_)); } [Fact] public void EnumAccessibilityNoChange() { var src1 = "internal enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Color { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Fact] public void EnumInitializerUpdate() { var src1 = "enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Color { Red = 1, Blue = 3, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Blue = 2]@22 -> [Blue = 3]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, "Blue = 3", FeaturesResources.enum_value)); } [Fact] public void EnumInitializerUpdate2() { var src1 = "enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Color { Red = 1 << 0, Blue = 2 << 1, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [Red = 1]@13 -> [Red = 1 << 0]@13", "Update [Blue = 2]@22 -> [Blue = 2 << 1]@27"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, "Blue = 2 << 1", FeaturesResources.enum_value)); } [Fact] public void EnumInitializerUpdate3() { var src1 = "enum Color { Red = int.MinValue }"; var src2 = "enum Color { Red = int.MaxValue }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [Red = int.MinValue]@13 -> [Red = int.MaxValue]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, "Red = int.MaxValue", FeaturesResources.enum_value)); } [Fact] public void EnumInitializerUpdate_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]enum Color { Red = 1 }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]enum Color { Red = 2 }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [Red = 1]@185 -> [Red = 2]@185"); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("Color"))); } [Fact] public void EnumInitializerAdd() { var src1 = "enum Color { Red, }"; var src2 = "enum Color { Red = 1, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Red]@13 -> [Red = 1]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, "Red = 1", FeaturesResources.enum_value)); } [Fact] public void EnumInitializerDelete() { var src1 = "enum Color { Red = 1, }"; var src2 = "enum Color { Red, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Red = 1]@13 -> [Red]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, "Red", FeaturesResources.enum_value)); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916")] [Fact] public void EnumMemberAdd() { var src1 = "enum Color { Red }"; var src2 = "enum Color { Red, Blue}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum Color { Red }]@0 -> [enum Color { Red, Blue}]@0", "Insert [Blue]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "Blue", FeaturesResources.enum_value)); } [Fact] public void EnumMemberAdd2() { var src1 = "enum Color { Red, }"; var src2 = "enum Color { Red, Blue}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [Blue]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "Blue", FeaturesResources.enum_value)); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916")] [Fact] public void EnumMemberAdd3() { var src1 = "enum Color { Red, }"; var src2 = "enum Color { Red, Blue,}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color { Red, }]@0 -> [enum Color { Red, Blue,}]@0", "Insert [Blue]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "Blue", FeaturesResources.enum_value)); } [Fact] public void EnumMemberUpdate() { var src1 = "enum Color { Red }"; var src2 = "enum Color { Orange }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Red]@13 -> [Orange]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "Orange", FeaturesResources.enum_value)); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916")] [Fact] public void EnumMemberDelete() { var src1 = "enum Color { Red, Blue}"; var src2 = "enum Color { Red }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum Color { Red, Blue}]@0 -> [enum Color { Red }]@0", "Delete [Blue]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "enum Color", DeletedSymbolDisplay(FeaturesResources.enum_value, "Blue"))); } [Fact] public void EnumMemberDelete2() { var src1 = "enum Color { Red, Blue}"; var src2 = "enum Color { Red, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [Blue]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "enum Color", DeletedSymbolDisplay(FeaturesResources.enum_value, "Blue"))); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916"), WorkItem(793197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/793197")] [Fact] public void EnumTrailingCommaAdd() { var src1 = "enum Color { Red }"; var src2 = "enum Color { Red, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum Color { Red }]@0 -> [enum Color { Red, }]@0"); edits.VerifySemantics(ActiveStatementsDescription.Empty, NoSemanticEdits); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916"), WorkItem(793197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/793197")] [Fact] public void EnumTrailingCommaAdd_WithInitializer() { var src1 = "enum Color { Red = 1 }"; var src2 = "enum Color { Red = 1, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum Color { Red = 1 }]@0 -> [enum Color { Red = 1, }]@0"); edits.VerifySemantics(ActiveStatementsDescription.Empty, NoSemanticEdits); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916"), WorkItem(793197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/793197")] [Fact] public void EnumTrailingCommaDelete() { var src1 = "enum Color { Red, }"; var src2 = "enum Color { Red }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color { Red, }]@0 -> [enum Color { Red }]@0"); edits.VerifySemantics(ActiveStatementsDescription.Empty, NoSemanticEdits); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916"), WorkItem(793197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/793197")] [Fact] public void EnumTrailingCommaDelete_WithInitializer() { var src1 = "enum Color { Red = 1, }"; var src2 = "enum Color { Red = 1 }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color { Red = 1, }]@0 -> [enum Color { Red = 1 }]@0"); edits.VerifySemantics(ActiveStatementsDescription.Empty, NoSemanticEdits); } #endregion #region Delegates [Fact] public void Delegates_NoModifiers_Insert() { var src1 = ""; var src2 = "delegate void D();"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_NoModifiers_IntoNamespace_Insert() { var src1 = "namespace N { }"; var src2 = "namespace N { delegate void D(); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_NoModifiers_IntoType_Insert() { var src1 = "class C { }"; var src2 = "class C { delegate void D(); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_Public_IntoType_Insert() { var src1 = "class C { }"; var src2 = "class C { public delegate void D(); }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [public delegate void D();]@10", "Insert [()]@32"); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_Generic_Insert() { var src1 = "class C { }"; var src2 = "class C { private delegate void D<T>(T a); }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [private delegate void D<T>(T a);]@10", "Insert [<T>]@33", "Insert [(T a)]@36", "Insert [T]@34", "Insert [T a]@37"); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_Delete() { var src1 = "class C { private delegate void D(); }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [private delegate void D();]@10", "Delete [()]@33"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.delegate_, "D"))); } [Fact] public void Delegates_Rename() { var src1 = "public delegate void D();"; var src2 = "public delegate void Z();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate void D();]@0 -> [public delegate void Z();]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "public delegate void Z()", FeaturesResources.delegate_)); } [Fact] public void Delegates_Accessibility_Update() { var src1 = "public delegate void D();"; var src2 = "private delegate void D();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate void D();]@0 -> [private delegate void D();]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "private delegate void D()", FeaturesResources.delegate_)); } [Fact] public void Delegates_ReturnType_Update() { var src1 = "public delegate int D();"; var src2 = "public delegate void D();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate int D();]@0 -> [public delegate void D();]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "public delegate void D()", FeaturesResources.delegate_)); } [Fact] public void Delegates_ReturnType_AddAttribute() { var attribute = "public class A : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D(int a);"; var src2 = attribute + "[return: A]public delegate int D(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate int D(int a);]@39 -> [[return: A]public delegate int D(int a);]@39"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.Invoke")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.BeginInvoke")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Delegates_Parameter_Insert() { var src1 = "public delegate int D();"; var src2 = "public delegate int D(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [int a]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "int a", FeaturesResources.parameter)); } [Fact] public void Delegates_Parameter_Insert_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]public delegate int D();"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]internal delegate bool D(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("D"))); } [Fact] public void Delegates_Parameter_Delete() { var src1 = "public delegate int D(int a);"; var src2 = "public delegate int D();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [int a]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "public delegate int D()", DeletedSymbolDisplay(FeaturesResources.parameter, "int a"))); } [Fact] public void Delegates_Parameter_Rename() { var src1 = "public delegate int D(int a);"; var src2 = "public delegate int D(int b);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@22 -> [int b]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "int b", FeaturesResources.parameter)); } [Fact] public void Delegates_Parameter_Update() { var src1 = "public delegate int D(int a);"; var src2 = "public delegate int D(byte a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@22 -> [byte a]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "byte a", FeaturesResources.parameter)); } [Fact] public void Delegates_Parameter_AddAttribute_NotSupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D(int a);"; var src2 = attribute + "public delegate int D([A]int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@70 -> [[A]int a]@70"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Delegates_Parameter_AddAttribute() { var attribute = "public class A : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D(int a);"; var src2 = attribute + "public delegate int D([A]int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@61 -> [[A]int a]@61"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.Invoke")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.BeginInvoke")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Delegates_TypeParameter_Insert() { var src1 = "public delegate int D();"; var src2 = "public delegate int D<T>();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [<T>]@21", "Insert [T]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "T", FeaturesResources.type_parameter)); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/54881")] [WorkItem(54881, "https://github.com/dotnet/roslyn/issues/54881")] public void Delegates_TypeParameter_Insert_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]public delegate int D<out T>();"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]internal delegate bool D<in T, out S>(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("D"))); } [Fact] public void Delegates_TypeParameter_Delete() { var src1 = "public delegate int D<T>();"; var src2 = "public delegate int D();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [<T>]@21", "Delete [T]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "public delegate int D()", DeletedSymbolDisplay(FeaturesResources.type_parameter, "T"))); } [Fact] public void Delegates_TypeParameter_Rename() { var src1 = "public delegate int D<T>();"; var src2 = "public delegate int D<S>();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [T]@22 -> [S]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "S", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "S")); } [Fact] public void Delegates_TypeParameter_Variance1() { var src1 = "public delegate int D<T>();"; var src2 = "public delegate int D<in T>();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [T]@22 -> [in T]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.VarianceUpdate, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void Delegates_TypeParameter_Variance2() { var src1 = "public delegate int D<out T>();"; var src2 = "public delegate int D<T>();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [out T]@22 -> [T]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.VarianceUpdate, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void Delegates_TypeParameter_Variance3() { var src1 = "public delegate int D<out T>();"; var src2 = "public delegate int D<in T>();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [out T]@22 -> [in T]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.VarianceUpdate, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void Delegates_TypeParameter_AddAttribute() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D<T>();"; var src2 = attribute + "public delegate int D<[A]T>();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [T]@70 -> [[A]T]@70"); edits.VerifyRudeDiagnostics( EditAndContinueTestHelpers.Net6RuntimeCapabilities, Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void Delegates_Attribute_Add_NotSupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D(int a);"; var src2 = attribute + "[A]public delegate int D(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate int D(int a);]@48 -> [[A]public delegate int D(int a);]@48"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "public delegate int D(int a)", FeaturesResources.delegate_)); } [Fact] public void Delegates_Attribute_Add() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D(int a);"; var src2 = attribute + "[A]public delegate int D(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate int D(int a);]@48 -> [[A]public delegate int D(int a);]@48"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Delegates_Attribute_Add_WithReturnTypeAttribute() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D(int a);"; var src2 = attribute + "[return: A][A]public delegate int D(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate int D(int a);]@48 -> [[return: A][A]public delegate int D(int a);]@48"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.Invoke")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.BeginInvoke")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Delegates_ReadOnlyRef_Parameter_InsertWhole() { var src1 = ""; var src2 = "public delegate int D(in int b);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [public delegate int D(in int b);]@0", "Insert [(in int b)]@21", "Insert [in int b]@22"); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_ReadOnlyRef_Parameter_InsertParameter() { var src1 = "public delegate int D();"; var src2 = "public delegate int D(in int b);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [in int b]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "in int b", FeaturesResources.parameter)); } [Fact] public void Delegates_ReadOnlyRef_Parameter_Update() { var src1 = "public delegate int D(int b);"; var src2 = "public delegate int D(in int b);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int b]@22 -> [in int b]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "in int b", FeaturesResources.parameter)); } [Fact] public void Delegates_ReadOnlyRef_ReturnType_Insert() { var src1 = ""; var src2 = "public delegate ref readonly int D();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [public delegate ref readonly int D();]@0", "Insert [()]@34"); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_ReadOnlyRef_ReturnType_Update() { var src1 = "public delegate int D();"; var src2 = "public delegate ref readonly int D();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate int D();]@0 -> [public delegate ref readonly int D();]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "public delegate ref readonly int D()", FeaturesResources.delegate_)); } #endregion #region Nested Types [Fact] public void NestedClass_ClassMove1() { var src1 = @"class C { class D { } }"; var src2 = @"class C { } class D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Move [class D { }]@10 -> @12"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "class D", FeaturesResources.class_)); } [Fact] public void NestedClass_ClassMove2() { var src1 = @"class C { class D { } class E { } class F { } }"; var src2 = @"class C { class D { } class F { } } class E { } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Move [class E { }]@23 -> @37"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "class E", FeaturesResources.class_)); } [Fact] public void NestedClass_ClassInsertMove1() { var src1 = @"class C { class D { } }"; var src2 = @"class C { class E { class D { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [class E { class D { } }]@10", "Move [class D { }]@10 -> @20"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "class D", FeaturesResources.class_)); } [Fact] public void NestedClass_Insert1() { var src1 = @"class C { }"; var src2 = @"class C { class D { class E { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [class D { class E { } }]@10", "Insert [class E { }]@20"); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedClass_Insert2() { var src1 = @"class C { }"; var src2 = @"class C { protected class D { public class E { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [protected class D { public class E { } }]@10", "Insert [public class E { }]@30"); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedClass_Insert3() { var src1 = @"class C { }"; var src2 = @"class C { private class D { public class E { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [private class D { public class E { } }]@10", "Insert [public class E { }]@28"); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedClass_Insert4() { var src1 = @"class C { }"; var src2 = @"class C { private class D { public D(int a, int b) { } public int P { get; set; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [private class D { public D(int a, int b) { } public int P { get; set; } }]@10", "Insert [public D(int a, int b) { }]@28", "Insert [public int P { get; set; }]@55", "Insert [(int a, int b)]@36", "Insert [{ get; set; }]@68", "Insert [int a]@37", "Insert [int b]@44", "Insert [get;]@70", "Insert [set;]@75"); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedClass_Insert_ReloadableIntoReloadable1() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { [CreateNewOnMetadataUpdate]class D { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void NestedClass_Insert_ReloadableIntoReloadable2() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { [CreateNewOnMetadataUpdate]class D { [CreateNewOnMetadataUpdate]class E { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void NestedClass_Insert_ReloadableIntoReloadable3() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { class D { [CreateNewOnMetadataUpdate]class E { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void NestedClass_Insert_ReloadableIntoReloadable4() { var src1 = ReloadableAttributeSrc + "class C { }"; var src2 = ReloadableAttributeSrc + "class C { [CreateNewOnMetadataUpdate]class D { [CreateNewOnMetadataUpdate]class E { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.D"))); } [Fact] public void NestedClass_Insert_Member_Reloadable() { var src1 = ReloadableAttributeSrc + "class C { [CreateNewOnMetadataUpdate]class D { } }"; var src2 = ReloadableAttributeSrc + "class C { [CreateNewOnMetadataUpdate]class D { int x; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C.D"))); } [Fact] public void NestedClass_InsertMemberWithInitializer1() { var src1 = @" class C { }"; var src2 = @" class C { private class D { public int P = 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.D"), preserveLocalVariables: false) }); } [WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] [Fact] public void NestedClass_Insert_PInvoke() { var src1 = @" using System; using System.Runtime.InteropServices; class C { }"; var src2 = @" using System; using System.Runtime.InteropServices; class C { abstract class D { public extern D(); public static extern int P { [DllImport(""msvcrt.dll"")]get; [DllImport(""msvcrt.dll"")]set; } [DllImport(""msvcrt.dll"")] public static extern int puts(string c); [DllImport(""msvcrt.dll"")] public static extern int operator +(D d, D g); [DllImport(""msvcrt.dll"")] public static extern explicit operator int (D d); } } "; var edits = GetTopEdits(src1, src2); // Adding P/Invoke is not supported by the CLR. edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertExtern, "public extern D()", FeaturesResources.constructor), Diagnostic(RudeEditKind.InsertExtern, "public static extern int P", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertExtern, "public static extern int puts(string c)", FeaturesResources.method), Diagnostic(RudeEditKind.InsertExtern, "public static extern int operator +(D d, D g)", FeaturesResources.operator_), Diagnostic(RudeEditKind.InsertExtern, "public static extern explicit operator int (D d)", CSharpFeaturesResources.conversion_operator)); } [WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] [Fact] public void NestedClass_Insert_VirtualAbstract() { var src1 = @" using System; using System.Runtime.InteropServices; class C { }"; var src2 = @" using System; using System.Runtime.InteropServices; class C { abstract class D { public abstract int P { get; } public abstract int this[int i] { get; } public abstract int puts(string c); public virtual event Action E { add { } remove { } } public virtual int Q { get { return 1; } } public virtual int this[string i] { get { return 1; } } public virtual int M(string c) { return 1; } } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedClass_TypeReorder1() { var src1 = @"class C { struct E { } class F { } delegate void D(); interface I {} }"; var src2 = @"class C { class F { } interface I {} delegate void D(); struct E { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [struct E { }]@10 -> @56", "Reorder [interface I {}]@54 -> @22"); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedClass_MethodDeleteInsert() { var src1 = @"public class C { public void goo() {} }"; var src2 = @"public class C { private class D { public void goo() {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [private class D { public void goo() {} }]@17", "Insert [public void goo() {}]@35", "Insert [()]@50", "Delete [public void goo() {}]@17", "Delete [()]@32"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "public class C", DeletedSymbolDisplay(FeaturesResources.method, "goo()"))); } [Fact] public void NestedClass_ClassDeleteInsert() { var src1 = @"public class C { public class X {} }"; var src2 = @"public class C { public class D { public class X {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [public class D { public class X {} }]@17", "Move [public class X {}]@17 -> @34"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "public class X", FeaturesResources.class_)); } /// <summary> /// A new generic type can be added whether it's nested and inherits generic parameters from the containing type, or top-level. /// </summary> [Fact] public void NestedClassGeneric_Insert() { var src1 = @" using System; class C<T> { } "; var src2 = @" using System; class C<T> { class D {} struct S {} enum N {} interface I {} delegate void D(); } class D<T> { } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedEnum_InsertMember() { var src1 = "struct S { enum N { A = 1 } }"; var src2 = "struct S { enum N { A = 1, B = 2 } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum N { A = 1 }]@11 -> [enum N { A = 1, B = 2 }]@11", "Insert [B = 2]@27"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "B = 2", FeaturesResources.enum_value)); } [Fact, WorkItem(50876, "https://github.com/dotnet/roslyn/issues/50876")] public void NestedEnumInPartialType_InsertDelete() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { enum N { A = 1 } }"; var srcA2 = "partial struct S { enum N { A = 1 } }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults() }); } [Fact, WorkItem(50876, "https://github.com/dotnet/roslyn/issues/50876")] public void NestedEnumInPartialType_InsertDeleteAndUpdateMember() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { enum N { A = 1 } }"; var srcA2 = "partial struct S { enum N { A = 2 } }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.InitializerUpdate, "A = 2", FeaturesResources.enum_value), }), DocumentResults() }); } [Fact, WorkItem(50876, "https://github.com/dotnet/roslyn/issues/50876")] public void NestedEnumInPartialType_InsertDeleteAndUpdateBase() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { enum N : uint { A = 1 } }"; var srcA2 = "partial struct S { enum N : int { A = 1 } }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.EnumUnderlyingTypeUpdate, "enum N", FeaturesResources.enum_), }), DocumentResults() }); } [Fact, WorkItem(50876, "https://github.com/dotnet/roslyn/issues/50876")] public void NestedEnumInPartialType_InsertDeleteAndInsertMember() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { enum N { A = 1 } }"; var srcA2 = "partial struct S { enum N { A = 1, B = 2 } }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Insert, "B = 2", FeaturesResources.enum_value) }), DocumentResults() }); } [Fact] public void NestedDelegateInPartialType_InsertDelete() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { delegate void D(); }"; var srcA2 = "partial struct S { delegate void D(); }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( // delegate does not have any user-defined method body and this does not need a PDB update semanticEdits: NoSemanticEdits), DocumentResults() }); } [Fact] public void NestedDelegateInPartialType_InsertDeleteAndChangeParameters() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { delegate void D(); }"; var srcA2 = "partial struct S { delegate void D(int x); }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.ChangingParameterTypes, "delegate void D(int x)", FeaturesResources.delegate_) }), DocumentResults() }); } [Fact] public void NestedDelegateInPartialType_InsertDeleteAndChangeReturnType() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { delegate ref int D(); }"; var srcA2 = "partial struct S { delegate ref readonly int D(); }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.TypeUpdate, "delegate ref readonly int D()", FeaturesResources.delegate_) }), DocumentResults() }); } [Fact] public void NestedDelegateInPartialType_InsertDeleteAndChangeOptionalParameterValue() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { delegate void D(int x = 1); }"; var srcA2 = "partial struct S { delegate void D(int x = 2); }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.InitializerUpdate, "int x = 2", FeaturesResources.parameter) }), DocumentResults() }); } [Fact] public void NestedPartialTypeInPartialType_InsertDeleteAndChange() { var srcA1 = "partial struct S { partial class C { void F1() {} } }"; var srcB1 = "partial struct S { partial class C { void F2(byte x) {} } }"; var srcC1 = "partial struct S { }"; var srcA2 = "partial struct S { partial class C { void F1() {} } }"; var srcB2 = "partial struct S { }"; var srcC2 = "partial struct S { partial class C { void F2(int x) {} } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial struct S", DeletedSymbolDisplay(FeaturesResources.method, "F2(byte x)")) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("S").GetMember<INamedTypeSymbol>("C").GetMember("F2")) }) }); } [Fact] public void Type_Partial_AddMultiple() { var srcA1 = ""; var srcB1 = ""; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C"), partialType: "C") }), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C"), partialType: "C") }), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Type_Partial_InsertDeleteAndChange_Attribute() { var srcA1 = "partial class C { }"; var srcB1 = ""; var srcC1 = "partial class C { }"; var srcA2 = ""; var srcB2 = "[A]partial class C { }"; var srcC2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C"), partialType: "C") }), DocumentResults(), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Type_Partial_InsertDeleteAndChange_TypeParameterAttribute_NotSupportedByRuntime() { var srcA1 = "partial class C<T> { }"; var srcB1 = ""; var srcC1 = "partial class C<T> { }"; var srcA2 = ""; var srcB2 = "partial class C<[A]T> { }"; var srcC2 = "partial class C<T> { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "partial class C<[A]T>"), Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T") }), DocumentResults(), }); } [Fact] public void Type_Partial_InsertDeleteAndChange_Constraint() { var srcA1 = "partial class C<T> { }"; var srcB1 = ""; var srcC1 = "partial class C<T> { }"; var srcA2 = ""; var srcB2 = "partial class C<T> where T : new() { }"; var srcC2 = "partial class C<T> { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "partial class C<T>"), Diagnostic(RudeEditKind.ChangingConstraints, "where T : new()", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "where T : new()") }), DocumentResults(), }); } [Fact] public void Type_Partial_InsertDeleteRefactor() { var srcA1 = "partial class C : I { void F() { } }"; var srcB1 = "[A][B]partial class C : J { void G() { } }"; var srcC1 = ""; var srcD1 = ""; var srcA2 = ""; var srcB2 = ""; var srcC2 = "[A]partial class C : I, J { void F() { } }"; var srcD2 = "[B]partial class C { void G() { } }"; var srcE = "interface I {} interface J {}"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2), GetTopEdits(srcD1, srcD2), GetTopEdits(srcE, srcE) }, new[] { DocumentResults(), DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F")) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("G")) }), DocumentResults(), }); } [Fact] public void Type_Partial_Attribute_AddMultiple() { var attributes = @" class A : System.Attribute {} class B : System.Attribute {} "; var srcA1 = "partial class C { }" + attributes; var srcB1 = "partial class C { }"; var srcA2 = "[A]partial class C { }" + attributes; var srcB2 = "[B]partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C"), partialType: "C") }), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C"), partialType: "C") }), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Type_Partial_InsertDeleteRefactor_AttributeListSplitting() { var srcA1 = "partial class C { void F() { } }"; var srcB1 = "[A,B]partial class C { void G() { } }"; var srcC1 = ""; var srcD1 = ""; var srcA2 = ""; var srcB2 = ""; var srcC2 = "[A]partial class C { void F() { } }"; var srcD2 = "[B]partial class C { void G() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2), GetTopEdits(srcD1, srcD2) }, new[] { DocumentResults(), DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")) }), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.G")) }), }); } [Fact] public void Type_Partial_InsertDeleteChangeMember() { var srcA1 = "partial class C { void F(int y = 1) { } }"; var srcB1 = "partial class C { void G(int x = 1) { } }"; var srcC1 = ""; var srcA2 = ""; var srcB2 = "partial class C { void G(int x = 2) { } }"; var srcC2 = "partial class C { void F(int y = 2) { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.InitializerUpdate, "int x = 2", FeaturesResources.parameter) }), DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.InitializerUpdate, "int y = 2", FeaturesResources.parameter) }), }); } [Fact] public void NestedPartialTypeInPartialType_InsertDeleteAndInsertVirtual() { var srcA1 = "partial interface I { partial class C { virtual void F1() {} } }"; var srcB1 = "partial interface I { partial class C { virtual void F2() {} } }"; var srcC1 = "partial interface I { partial class C { } }"; var srcD1 = "partial interface I { partial class C { } }"; var srcE1 = "partial interface I { }"; var srcF1 = "partial interface I { }"; var srcA2 = "partial interface I { partial class C { } }"; var srcB2 = ""; var srcC2 = "partial interface I { partial class C { virtual void F1() {} } }"; // move existing virtual into existing partial decl var srcD2 = "partial interface I { partial class C { virtual void N1() {} } }"; // insert new virtual into existing partial decl var srcE2 = "partial interface I { partial class C { virtual void F2() {} } }"; // move existing virtual into a new partial decl var srcF2 = "partial interface I { partial class C { virtual void N2() {} } }"; // insert new virtual into new partial decl EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2), GetTopEdits(srcD1, srcD2), GetTopEdits(srcE1, srcE2), GetTopEdits(srcF1, srcF2) }, new[] { // A DocumentResults(), // B DocumentResults(), // C DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember<INamedTypeSymbol>("C").GetMember("F1")) }), // D DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.InsertVirtual, "virtual void N1()", FeaturesResources.method) }), // E DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember<INamedTypeSymbol>("C").GetMember("F2")) }), // F DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.InsertVirtual, "virtual void N2()", FeaturesResources.method) }), }); } #endregion #region Namespaces [Fact] public void Namespace_Insert() { var src1 = @""; var src2 = @"namespace C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [namespace C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "namespace C", FeaturesResources.namespace_)); } [Fact] public void Namespace_InsertNested() { var src1 = @"namespace C { }"; var src2 = @"namespace C { namespace D { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [namespace D { }]@14"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "namespace D", FeaturesResources.namespace_)); } [Fact] public void Namespace_DeleteNested() { var src1 = @"namespace C { namespace D { } }"; var src2 = @"namespace C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [namespace D { }]@14"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "namespace C", FeaturesResources.namespace_)); } [Fact] public void Namespace_Move() { var src1 = @"namespace C { namespace D { } }"; var src2 = @"namespace C { } namespace D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Move [namespace D { }]@14 -> @16"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "namespace D", FeaturesResources.namespace_)); } [Fact] public void Namespace_Reorder1() { var src1 = @"namespace C { namespace D { } class T { } namespace E { } }"; var src2 = @"namespace C { namespace E { } class T { } namespace D { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [class T { }]@30 -> @30", "Reorder [namespace E { }]@42 -> @14"); edits.VerifyRudeDiagnostics(); } [Fact] public void Namespace_Reorder2() { var src1 = @"namespace C { namespace D1 { } namespace D2 { } namespace D3 { } class T { } namespace E { } }"; var src2 = @"namespace C { namespace E { } class T { } namespace D1 { } namespace D2 { } namespace D3 { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [class T { }]@65 -> @65", "Reorder [namespace E { }]@77 -> @14"); edits.VerifyRudeDiagnostics(); } [Fact] public void Namespace_FileScoped_Insert() { var src1 = @""; var src2 = @"namespace C;"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [namespace C;]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "namespace C", FeaturesResources.namespace_)); } [Fact] public void Namespace_FileScoped_Delete() { var src1 = @"namespace C;"; var src2 = @""; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [namespace C;]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, null, FeaturesResources.namespace_)); } #endregion #region Members [Fact] public void PartialMember_DeleteInsert_SingleDocument() { var src1 = @" using System; partial class C { void M() {} int P1 { get; set; } int P2 { get => 1; set {} } int this[int i] { get => 1; set {} } int this[byte i] { get => 1; set {} } event Action E { add {} remove {} } event Action EF; int F1; int F2; } partial class C { } "; var src2 = @" using System; partial class C { } partial class C { void M() {} int P1 { get; set; } int P2 { get => 1; set {} } int this[int i] { get => 1; set {} } int this[byte i] { get => 1; set {} } event Action E { add {} remove {} } event Action EF; int F1, F2; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [void M() {}]@68", "Insert [int P1 { get; set; }]@85", "Insert [int P2 { get => 1; set {} }]@111", "Insert [int this[int i] { get => 1; set {} }]@144", "Insert [int this[byte i] { get => 1; set {} }]@186", "Insert [event Action E { add {} remove {} }]@229", "Insert [event Action EF;]@270", "Insert [int F1, F2;]@292", "Insert [()]@74", "Insert [{ get; set; }]@92", "Insert [{ get => 1; set {} }]@118", "Insert [[int i]]@152", "Insert [{ get => 1; set {} }]@160", "Insert [[byte i]]@194", "Insert [{ get => 1; set {} }]@203", "Insert [{ add {} remove {} }]@244", "Insert [Action EF]@276", "Insert [int F1, F2]@292", "Insert [get;]@94", "Insert [set;]@99", "Insert [get => 1;]@120", "Insert [set {}]@130", "Insert [int i]@153", "Insert [get => 1;]@162", "Insert [set {}]@172", "Insert [byte i]@195", "Insert [get => 1;]@205", "Insert [set {}]@215", "Insert [add {}]@246", "Insert [remove {}]@253", "Insert [EF]@283", "Insert [F1]@296", "Insert [F2]@300", "Delete [void M() {}]@43", "Delete [()]@49", "Delete [int P1 { get; set; }]@60", "Delete [{ get; set; }]@67", "Delete [get;]@69", "Delete [set;]@74", "Delete [int P2 { get => 1; set {} }]@86", "Delete [{ get => 1; set {} }]@93", "Delete [get => 1;]@95", "Delete [set {}]@105", "Delete [int this[int i] { get => 1; set {} }]@119", "Delete [[int i]]@127", "Delete [int i]@128", "Delete [{ get => 1; set {} }]@135", "Delete [get => 1;]@137", "Delete [set {}]@147", "Delete [int this[byte i] { get => 1; set {} }]@161", "Delete [[byte i]]@169", "Delete [byte i]@170", "Delete [{ get => 1; set {} }]@178", "Delete [get => 1;]@180", "Delete [set {}]@190", "Delete [event Action E { add {} remove {} }]@204", "Delete [{ add {} remove {} }]@219", "Delete [add {}]@221", "Delete [remove {}]@228", "Delete [event Action EF;]@245", "Delete [Action EF]@251", "Delete [EF]@258", "Delete [int F1;]@267", "Delete [int F1]@267", "Delete [F1]@271", "Delete [int F2;]@280", "Delete [int F2]@280", "Delete [F2]@284"); EditAndContinueValidation.VerifySemantics( new[] { edits }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("M"), preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P1").GetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P1").SetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P2").GetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P2").SetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.GetParameters().Single().Type.Name == "Int32").GetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.GetParameters().Single().Type.Name == "Int32").SetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.GetParameters().Single().Type.Name == "Byte").GetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.GetParameters().Single().Type.Name == "Byte").SetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E").AddMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E").RemoveMethod, preserveLocalVariables: false), }) }); } [Fact] public void PartialMember_InsertDelete_MultipleDocuments() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { void F() {} }"; var srcA2 = "partial class C { void F() {} }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F"), preserveLocalVariables: false) }), DocumentResults() }); } [Fact] public void PartialMember_DeleteInsert_MultipleDocuments() { var srcA1 = "partial class C { void F() {} }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { void F() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F"), preserveLocalVariables: false) }) }); } [Fact] public void PartialMember_DeleteInsert_GenericMethod() { var srcA1 = "partial class C { void F<T>() {} }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { void F<T>() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.GenericMethodUpdate, "void F<T>()"), Diagnostic(RudeEditKind.GenericMethodUpdate, "T") }) }); } [Fact] public void PartialMember_DeleteInsert_GenericType() { var srcA1 = "partial class C<T> { void F() {} }"; var srcB1 = "partial class C<T> { }"; var srcA2 = "partial class C<T> { }"; var srcB2 = "partial class C<T> { void F() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "void F()") }) }); } [Fact] public void PartialMember_DeleteInsert_Destructor() { var srcA1 = "partial class C { ~C() {} }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { ~C() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("Finalize"), preserveLocalVariables: false), }) }); } [Fact] public void PartialNestedType_InsertDeleteAndChange() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { class D { void M() {} } interface I { } }"; var srcA2 = "partial class C { class D : I { void M() {} } interface I { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class D", FeaturesResources.class_), }), DocumentResults() }); } [Fact, WorkItem(51011, "https://github.com/dotnet/roslyn/issues/51011")] public void PartialMember_RenameInsertDelete() { // The syntactic analysis for A and B produce rename edits since it doesn't see that the member was in fact moved. // TODO: Currently, we don't even pass rename edits to semantic analysis where we could handle them as updates. var srcA1 = "partial class C { void F1() {} }"; var srcB1 = "partial class C { void F2() {} }"; var srcA2 = "partial class C { void F2() {} }"; var srcB2 = "partial class C { void F1() {} }"; // current outcome: GetTopEdits(srcA1, srcA2).VerifyRudeDiagnostics(Diagnostic(RudeEditKind.Renamed, "void F2()", FeaturesResources.method)); GetTopEdits(srcB1, srcB2).VerifyRudeDiagnostics(Diagnostic(RudeEditKind.Renamed, "void F1()", FeaturesResources.method)); // correct outcome: //EditAndContinueValidation.VerifySemantics( // new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, // new[] // { // DocumentResults(semanticEdits: new[] // { // SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F2")), // }), // DocumentResults( // semanticEdits: new[] // { // SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F1")), // }) // }); } [Fact] public void PartialMember_DeleteInsert_UpdateMethodBodyError() { var srcA1 = @" using System.Collections.Generic; partial class C { IEnumerable<int> F() { yield return 1; } } "; var srcB1 = @" using System.Collections.Generic; partial class C { } "; var srcA2 = @" using System.Collections.Generic; partial class C { } "; var srcB2 = @" using System.Collections.Generic; partial class C { IEnumerable<int> F() { yield return 1; yield return 2; } } "; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.Insert, "yield return 2;", CSharpFeaturesResources.yield_return_statement) }) }); } [Fact] public void PartialMember_DeleteInsert_UpdatePropertyAccessors() { var srcA1 = "partial class C { int P { get => 1; set { Console.WriteLine(1); } } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int P { get => 2; set { Console.WriteLine(2); } } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod) }) }); } [Fact] public void PartialMember_DeleteInsert_UpdateAutoProperty() { var srcA1 = "partial class C { int P => 1; }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int P => 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod) }) }); } [Fact] public void PartialMember_DeleteInsert_AddFieldInitializer() { var srcA1 = "partial class C { int f; }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int f = 1; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }) }); } [Fact] public void PartialMember_DeleteInsert_RemoveFieldInitializer() { var srcA1 = "partial class C { int f = 1; }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int f; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }) }); } [Fact] public void PartialMember_DeleteInsert_ConstructorWithInitializers() { var srcA1 = "partial class C { int f = 1; C(int x) { f = x; } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { int f = 1; }"; var srcB2 = "partial class C { C(int x) { f = x + 1; } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }) }); } [Fact] public void PartialMember_DeleteInsert_MethodAddParameter() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { void F() {} }"; var srcA2 = "partial struct S { void F(int x) {} }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("S.F")) }), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial struct S", DeletedSymbolDisplay(FeaturesResources.method, "F()")) }) }); } [Fact] public void PartialMember_DeleteInsert_UpdateMethodParameterType() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { void F(int x); }"; var srcA2 = "partial struct S { void F(byte x); }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("S.F")) }), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial struct S", DeletedSymbolDisplay(FeaturesResources.method, "F(int x)")) }) }); } [Fact] public void PartialMember_DeleteInsert_MethodAddTypeParameter() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { void F(); }"; var srcA2 = "partial struct S { void F<T>(); }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.InsertGenericMethod, "void F<T>()", FeaturesResources.method) }), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial struct S", DeletedSymbolDisplay(FeaturesResources.method, "F()")) }) }); } #endregion #region Methods [Theory] [InlineData("static")] [InlineData("virtual")] [InlineData("abstract")] [InlineData("override")] [InlineData("sealed override", "override")] public void Method_Modifiers_Update(string oldModifiers, string newModifiers = "") { if (oldModifiers != "") { oldModifiers += " "; } if (newModifiers != "") { newModifiers += " "; } var src1 = "class C { " + oldModifiers + "int F() => 0; }"; var src2 = "class C { " + newModifiers + "int F() => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [" + oldModifiers + "int F() => 0;]@10 -> [" + newModifiers + "int F() => 0;]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, newModifiers + "int F()", FeaturesResources.method)); } [Fact] public void Method_NewModifier_Add() { var src1 = "class C { int F() => 0; }"; var src2 = "class C { new int F() => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [int F() => 0;]@10 -> [new int F() => 0;]@10"); // Currently, an edit is produced eventhough there is no metadata/IL change. Consider improving. edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F"))); } [Fact] public void Method_NewModifier_Remove() { var src1 = "class C { new int F() => 0; }"; var src2 = "class C { int F() => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [new int F() => 0;]@10 -> [int F() => 0;]@10"); // Currently, an edit is produced eventhough there is no metadata/IL change. Consider improving. edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F"))); } [Fact] public void Method_ReadOnlyModifier_Add_InMutableStruct() { var src1 = @" struct S { public int M() => 1; }"; var src2 = @" struct S { public readonly int M() => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public readonly int M()", FeaturesResources.method)); } [Fact] public void Method_ReadOnlyModifier_Add_InReadOnlyStruct1() { var src1 = @" readonly struct S { public int M() => 1; }"; var src2 = @" readonly struct S { public readonly int M() => 1; }"; var edits = GetTopEdits(src1, src2); // Currently, an edit is produced eventhough the body nor IsReadOnly attribute have changed. Consider improving. edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember<IMethodSymbol>("M"))); } [Fact] public void Method_ReadOnlyModifier_Add_InReadOnlyStruct2() { var src1 = @" readonly struct S { public int M() => 1; }"; var src2 = @" struct S { public readonly int M() => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "struct S", "struct")); } [Fact] public void Method_AsyncModifier_Remove() { var src1 = @" class Test { public async Task<int> WaitAsync() { return 1; } }"; var src2 = @" class Test { public Task<int> WaitAsync() { return Task.FromResult(1); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingFromAsynchronousToSynchronous, "public Task<int> WaitAsync()", FeaturesResources.method)); } [Fact] public void Method_AsyncModifier_Add() { var src1 = @" class Test { public Task<int> WaitAsync() { return 1; } }"; var src2 = @" class Test { public async Task<int> WaitAsync() { await Task.Delay(1000); return 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); VerifyPreserveLocalVariables(edits, preserveLocalVariables: false); } [Fact] public void Method_AsyncModifier_Add_NotSupported() { var src1 = @" class Test { public Task<int> WaitAsync() { return 1; } }"; var src2 = @" class Test { public async Task<int> WaitAsync() { await Task.Delay(1000); return 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.MakeMethodAsync, "public async Task<int> WaitAsync()")); } [Theory] [InlineData("string", "string?")] [InlineData("object", "dynamic")] [InlineData("(int a, int b)", "(int a, int c)")] public void Method_ReturnType_Update_RuntimeTypeUnchanged(string oldType, string newType) { var src1 = "class C { " + oldType + " M() => default; }"; var src2 = "class C { " + newType + " M() => default; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M"))); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void Method_ReturnType_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C { " + oldType + " M() => default; }"; var src2 = "class C { " + newType + " M() => default; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, newType + " M()", FeaturesResources.method)); } [Fact] public void Method_Update() { var src1 = @" class C { static void Main(string[] args) { int a = 1; int b = 2; System.Console.WriteLine(a + b); } } "; var src2 = @" class C { static void Main(string[] args) { int b = 2; int a = 1; System.Console.WriteLine(a + b); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Update [static void Main(string[] args) { int a = 1; int b = 2; System.Console.WriteLine(a + b); }]@18 -> [static void Main(string[] args) { int b = 2; int a = 1; System.Console.WriteLine(a + b); }]@18"); edits.VerifyRudeDiagnostics(); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Main"), preserveLocalVariables: false) }); } [Fact] public void MethodWithExpressionBody_Update() { var src1 = @" class C { static int Main(string[] args) => F(1); static int F(int a) => 1; } "; var src2 = @" class C { static int Main(string[] args) => F(2); static int F(int a) => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Update [static int Main(string[] args) => F(1);]@18 -> [static int Main(string[] args) => F(2);]@18"); edits.VerifyRudeDiagnostics(); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Main"), preserveLocalVariables: false) }); } [Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")] public void MethodWithExpressionBody_Update_LiftedParameter() { var src1 = @" using System; class C { int M(int a) => new Func<int>(() => a + 1)(); } "; var src2 = @" using System; class C { int M(int a) => new Func<int>(() => 2)(); // not capturing a anymore }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int M(int a) => new Func<int>(() => a + 1)();]@35 -> [int M(int a) => new Func<int>(() => 2)();]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a")); } [Fact] public void MethodWithExpressionBody_ToBlockBody() { var src1 = "class C { static int F(int a) => 1; }"; var src2 = "class C { static int F(int a) { return 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [static int F(int a) => 1;]@10 -> [static int F(int a) { return 2; }]@10"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: false) }); } [Fact] public void MethodWithBlockBody_ToExpressionBody() { var src1 = "class C { static int F(int a) { return 2; } }"; var src2 = "class C { static int F(int a) => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [static int F(int a) { return 2; }]@10 -> [static int F(int a) => 1;]@10"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: false) }); } [Fact] public void MethodWithLambda_Update() { var src1 = @" using System; class C { static void F() { Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; } } "; var src2 = @" using System; class C { static void F() { Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; Console.WriteLine(1); } }"; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), syntaxMap[0]) }); } [Fact] public void MethodUpdate_LocalVariableDeclaration() { var src1 = @" class C { static void Main(string[] args) { int x = 1; Console.WriteLine(x); } } "; var src2 = @" class C { static void Main(string[] args) { int x = 2; Console.WriteLine(x); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Update [static void Main(string[] args) { int x = 1; Console.WriteLine(x); }]@18 -> [static void Main(string[] args) { int x = 2; Console.WriteLine(x); }]@18"); } [Fact] public void Method_Delete() { var src1 = @" class C { void goo() { } } "; var src2 = @" class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [void goo() { }]@18", "Delete [()]@26"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.method, "goo()"))); } [Fact] public void MethodWithExpressionBody_Delete() { var src1 = @" class C { int goo() => 1; } "; var src2 = @" class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [int goo() => 1;]@18", "Delete [()]@25"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.method, "goo()"))); } [WorkItem(754853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754853")] [Fact] public void MethodDelete_WithParameterAndAttribute() { var src1 = @" class C { [Obsolete] void goo(int a) { } } "; var src2 = @" class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Delete [[Obsolete] void goo(int a) { }]@18", "Delete [(int a)]@42", "Delete [int a]@43"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.method, "goo(int a)"))); } [WorkItem(754853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754853")] [Fact] public void MethodDelete_PInvoke() { var src1 = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] public static extern int puts(string c); } "; var src2 = @" using System; using System.Runtime.InteropServices; class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Delete [[DllImport(""msvcrt.dll"")] public static extern int puts(string c);]@74", "Delete [(string c)]@134", "Delete [string c]@135"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.method, "puts(string c)"))); } [Fact] public void MethodInsert_NotSupportedByRuntime() { var src1 = "class C { }"; var src2 = "class C { void goo() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "void goo()", FeaturesResources.method)); } [Fact] public void PrivateMethodInsert() { var src1 = @" class C { static void Main(string[] args) { Console.ReadLine(); } }"; var src2 = @" class C { void goo() { } static void Main(string[] args) { Console.ReadLine(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [void goo() { }]@18", "Insert [()]@26"); edits.VerifyRudeDiagnostics(); } [WorkItem(755784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784")] [Fact] public void PrivateMethodInsert_WithParameters() { var src1 = @" using System; class C { static void Main(string[] args) { Console.ReadLine(); } }"; var src2 = @" using System; class C { void goo(int a) { } static void Main(string[] args) { Console.ReadLine(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [void goo(int a) { }]@35", "Insert [(int a)]@43", "Insert [int a]@44"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.goo")) }); } [WorkItem(755784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784")] [Fact] public void PrivateMethodInsert_WithAttribute() { var src1 = @" class C { static void Main(string[] args) { Console.ReadLine(); } }"; var src2 = @" class C { [System.Obsolete] void goo(int a) { } static void Main(string[] args) { Console.ReadLine(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Insert [[System.Obsolete] void goo(int a) { }]@18", "Insert [(int a)]@49", "Insert [int a]@50"); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodInsert_Virtual() { var src1 = @" class C { }"; var src2 = @" class C { public virtual void F() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertVirtual, "public virtual void F()", FeaturesResources.method)); } [Fact] public void MethodInsert_Abstract() { var src1 = @" abstract class C { }"; var src2 = @" abstract class C { public abstract void F(); } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertVirtual, "public abstract void F()", FeaturesResources.method)); } [Fact] public void MethodInsert_Override() { var src1 = @" class C { }"; var src2 = @" class C { public override void F() { } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertVirtual, "public override void F()", FeaturesResources.method)); } [WorkItem(755784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784"), WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] [Fact] public void ExternMethodInsert() { var src1 = @" using System; using System.Runtime.InteropServices; class C { }"; var src2 = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] private static extern int puts(string c); } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Insert [[DllImport(""msvcrt.dll"")] private static extern int puts(string c);]@74", "Insert [(string c)]@135", "Insert [string c]@136"); // CLR doesn't support methods without a body edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertExtern, "private static extern int puts(string c)", FeaturesResources.method)); } [Fact] [WorkItem(755784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784"), WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] public void ExternMethodDeleteInsert() { var srcA1 = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] private static extern int puts(string c); }"; var srcA2 = @" using System; using System.Runtime.InteropServices; "; var srcB1 = @" using System; using System.Runtime.InteropServices; "; var srcB2 = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] private static extern int puts(string c); } "; // TODO: The method does not need to be updated since there are no sequence points generated for it. EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.puts")), }) }); } [Fact] [WorkItem(755784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784"), WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] public void ExternMethod_Attribute_DeleteInsert() { var srcA1 = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] private static extern int puts(string c); }"; var srcA2 = @" using System; using System.Runtime.InteropServices; "; var srcB1 = @" using System; using System.Runtime.InteropServices; "; var srcB2 = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] [Obsolete] private static extern int puts(string c); } "; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.puts")), }) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void MethodReorder1() { var src1 = "class C { void f(int a, int b) { a = b; } void g() { } }"; var src2 = "class C { void g() { } void f(int a, int b) { a = b; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Reorder [void g() { }]@42 -> @10"); } [Fact] public void MethodInsertDelete1() { var src1 = "class C { class D { } void f(int a, int b) { a = b; } }"; var src2 = "class C { class D { void f(int a, int b) { a = b; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [void f(int a, int b) { a = b; }]@20", "Insert [(int a, int b)]@26", "Insert [int a]@27", "Insert [int b]@34", "Delete [void f(int a, int b) { a = b; }]@22", "Delete [(int a, int b)]@28", "Delete [int a]@29", "Delete [int b]@36"); } [Fact] public void MethodUpdate_AddParameter() { var src1 = @" class C { static void Main() { } }"; var src2 = @" class C { static void Main(string[] args) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [string[] args]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "string[] args", FeaturesResources.parameter)); } [Fact] public void MethodUpdate_UpdateParameter() { var src1 = @" class C { static void Main(string[] args) { } }"; var src2 = @" class C { static void Main(string[] b) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [string[] args]@35 -> [string[] b]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "string[] b", FeaturesResources.parameter)); } [Fact] public void Method_Name_Update() { var src1 = @" class C { static void Main(string[] args) { } }"; var src2 = @" class C { static void EntryPoint(string[] args) { } }"; var edits = GetTopEdits(src1, src2); var expectedEdit = @"Update [static void Main(string[] args) { }]@18 -> [static void EntryPoint(string[] args) { }]@18"; edits.VerifyEdits(expectedEdit); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "static void EntryPoint(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_AsyncMethod0() { var src1 = @" class Test { public async Task<int> WaitAsync() { await Task.Delay(1000); return 1; } }"; var src2 = @" class Test { public async Task<int> WaitAsync() { await Task.Delay(500); return 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); VerifyPreserveLocalVariables(edits, preserveLocalVariables: true); } [Fact] public void MethodUpdate_AsyncMethod1() { var src1 = @" class Test { static void Main(string[] args) { Test f = new Test(); string result = f.WaitAsync().Result; } public async Task<string> WaitAsync() { await Task.Delay(1000); return ""Done""; } }"; var src2 = @" class Test { static void Main(string[] args) { Test f = new Test(); string result = f.WaitAsync().Result; } public async Task<string> WaitAsync() { await Task.Delay(1000); return ""Not Done""; } }"; var edits = GetTopEdits(src1, src2); var expectedEdit = @"Update [public async Task<string> WaitAsync() { await Task.Delay(1000); return ""Done""; }]@151 -> [public async Task<string> WaitAsync() { await Task.Delay(1000); return ""Not Done""; }]@151"; edits.VerifyEdits(expectedEdit); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_AddReturnTypeAttribute() { var src1 = @" using System; class Test { static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [return: Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(@"Update [static void Main(string[] args) { System.Console.Write(5); }]@38 -> [[return: Obsolete] static void Main(string[] args) { System.Console.Write(5); }]@38"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_AddAttribute() { var src1 = @" using System; class Test { static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(@"Update [static void Main(string[] args) { System.Console.Write(5); }]@38 -> [[Obsolete] static void Main(string[] args) { System.Console.Write(5); }]@38"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_AddAttribute_SupportedByRuntime() { var src1 = @" using System; class Test { static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(@"Update [static void Main(string[] args) { System.Console.Write(5); }]@38 -> [[Obsolete] static void Main(string[] args) { System.Console.Write(5); }]@38"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Test.Main")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void MethodUpdate_Attribute_ArrayParameter() { var src1 = @" class AAttribute : System.Attribute { public AAttribute(int[] nums) { } } class C { [A(new int[] { 1, 2, 3})] void M() { } }"; var src2 = @" class AAttribute : System.Attribute { public AAttribute(int[] nums) { } } class C { [A(new int[] { 4, 5, 6})] void M() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void MethodUpdate_Attribute_ArrayParameter_NoChange() { var src1 = @" class AAttribute : System.Attribute { public AAttribute(int[] nums) { } } class C { [A(new int[] { 1, 2, 3})] void M() { var x = 1; } }"; var src2 = @" class AAttribute : System.Attribute { public AAttribute(int[] nums) { } } class C { [A(new int[] { 1, 2, 3})] void M() { var x = 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M")) }); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_AddAttribute2() { var src1 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete, Serializable] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_AddAttribute3() { var src1 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete] [Serializable] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_AddAttribute4() { var src1 = @" using System; class Test { static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete, Serializable] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_UpdateAttribute() { var src1 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete("""")] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [WorkItem(754853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754853")] [Fact] public void MethodUpdate_DeleteAttribute() { var src1 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_DeleteAttribute2() { var src1 = @" using System; class Test { [Obsolete, Serializable] static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_DeleteAttribute3() { var src1 = @" using System; class Test { [Obsolete] [Serializable] static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_ExplicitlyImplemented1() { var src1 = @" class C : I, J { void I.Goo() { Console.WriteLine(2); } void J.Goo() { Console.WriteLine(1); } }"; var src2 = @" class C : I, J { void I.Goo() { Console.WriteLine(1); } void J.Goo() { Console.WriteLine(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void I.Goo() { Console.WriteLine(2); }]@25 -> [void I.Goo() { Console.WriteLine(1); }]@25", "Update [void J.Goo() { Console.WriteLine(1); }]@69 -> [void J.Goo() { Console.WriteLine(2); }]@69"); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_ExplicitlyImplemented2() { var src1 = @" class C : I, J { void I.Goo() { Console.WriteLine(1); } void J.Goo() { Console.WriteLine(2); } }"; var src2 = @" class C : I, J { void Goo() { Console.WriteLine(1); } void J.Goo() { Console.WriteLine(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void I.Goo() { Console.WriteLine(1); }]@25 -> [void Goo() { Console.WriteLine(1); }]@25"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "void Goo()", FeaturesResources.method)); } [WorkItem(754255, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754255")] [Fact] public void MethodUpdate_UpdateStackAlloc() { var src1 = @" class C { static void Main(string[] args) { int i = 10; unsafe { int* px2 = &i; } } }"; var src2 = @" class C { static void Main(string[] args) { int i = 10; unsafe { char* buffer = stackalloc char[16]; int* px2 = &i; } } }"; var expectedEdit = @"Update [static void Main(string[] args) { int i = 10; unsafe { int* px2 = &i; } }]@18 -> [static void Main(string[] args) { int i = 10; unsafe { char* buffer = stackalloc char[16]; int* px2 = &i; } }]@18"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(expectedEdit); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", FeaturesResources.method)); } [Theory] [InlineData("stackalloc int[3]")] [InlineData("stackalloc int[3] { 1, 2, 3 }")] [InlineData("stackalloc int[] { 1, 2, 3 }")] [InlineData("stackalloc[] { 1, 2, 3 }")] public void MethodUpdate_UpdateStackAlloc2(string stackallocDecl) { var src1 = @"unsafe class C { static int F() { var x = " + stackallocDecl + "; return 1; } }"; var src2 = @"unsafe class C { static int F() { var x = " + stackallocDecl + "; return 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", FeaturesResources.method)); } [Fact] public void MethodUpdate_UpdateStackAllocInLambda1() { var src1 = "unsafe class C { void M() { F(1, () => { int* a = stackalloc int[10]; }); } }"; var src2 = "unsafe class C { void M() { F(2, () => { int* a = stackalloc int[10]; }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_UpdateStackAllocInLambda2() { var src1 = "unsafe class C { void M() { F(1, x => { int* a = stackalloc int[10]; }); } }"; var src2 = "unsafe class C { void M() { F(2, x => { int* a = stackalloc int[10]; }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_UpdateStackAllocInAnonymousMethod() { var src1 = "unsafe class C { void M() { F(1, delegate(int x) { int* a = stackalloc int[10]; }); } }"; var src2 = "unsafe class C { void M() { F(2, delegate(int x) { int* a = stackalloc int[10]; }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_UpdateStackAllocInLocalFunction() { var src1 = "class C { void M() { unsafe void f(int x) { int* a = stackalloc int[10]; } f(1); } }"; var src2 = "class C { void M() { unsafe void f(int x) { int* a = stackalloc int[10]; } f(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_SwitchExpressionInLambda1() { var src1 = "class C { void M() { F(1, a => a switch { 0 => 0, _ => 2 }); } }"; var src2 = "class C { void M() { F(2, a => a switch { 0 => 0, _ => 2 }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_SwitchExpressionInLambda2() { var src1 = "class C { void M() { F(1, a => a switch { 0 => 0, _ => 2 }); } }"; var src2 = "class C { void M() { F(2, a => a switch { 0 => 0, _ => 2 }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_SwitchExpressionInAnonymousMethod() { var src1 = "class C { void M() { F(1, delegate(int a) { return a switch { 0 => 0, _ => 2 }; }); } }"; var src2 = "class C { void M() { F(2, delegate(int a) { return a switch { 0 => 0, _ => 2 }; }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_SwitchExpressionInLocalFunction() { var src1 = "class C { void M() { int f(int a) => a switch { 0 => 0, _ => 2 }; f(1); } }"; var src2 = "class C { void M() { int f(int a) => a switch { 0 => 0, _ => 2 }; f(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_SwitchExpressionInQuery() { var src1 = "class C { void M() { var x = from z in new[] { 1, 2, 3 } where z switch { 0 => true, _ => false } select z + 1; } }"; var src2 = "class C { void M() { var x = from z in new[] { 1, 2, 3 } where z switch { 0 => true, _ => false } select z + 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_UpdateAnonymousMethod() { var src1 = "class C { void M() { F(1, delegate(int a) { return a; }); } }"; var src2 = "class C { void M() { F(2, delegate(int a) { return a; }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodWithExpressionBody_Update_UpdateAnonymousMethod() { var src1 = "class C { void M() => F(1, delegate(int a) { return a; }); }"; var src2 = "class C { void M() => F(2, delegate(int a) { return a; }); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_Query() { var src1 = "class C { void M() { F(1, from goo in bar select baz); } }"; var src2 = "class C { void M() { F(2, from goo in bar select baz); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodWithExpressionBody_Update_Query() { var src1 = "class C { void M() => F(1, from goo in bar select baz); }"; var src2 = "class C { void M() => F(2, from goo in bar select baz); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_AnonymousType() { var src1 = "class C { void M() { F(1, new { A = 1, B = 2 }); } }"; var src2 = "class C { void M() { F(2, new { A = 1, B = 2 }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodWithExpressionBody_Update_AnonymousType() { var src1 = "class C { void M() => F(new { A = 1, B = 2 }); }"; var src2 = "class C { void M() => F(new { A = 10, B = 20 }); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_Iterator_YieldReturn() { var src1 = "class C { IEnumerable<int> M() { yield return 1; } }"; var src2 = "class C { IEnumerable<int> M() { yield return 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); VerifyPreserveLocalVariables(edits, preserveLocalVariables: true); } [Fact] public void MethodUpdate_AddYieldReturn() { var src1 = "class C { IEnumerable<int> M() { return new[] { 1, 2, 3}; } }"; var src2 = "class C { IEnumerable<int> M() { yield return 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); VerifyPreserveLocalVariables(edits, preserveLocalVariables: false); } [Fact] public void MethodUpdate_AddYieldReturn_NotSupported() { var src1 = "class C { IEnumerable<int> M() { return new[] { 1, 2, 3}; } }"; var src2 = "class C { IEnumerable<int> M() { yield return 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.MakeMethodIterator, "IEnumerable<int> M()")); } [Fact] public void MethodUpdate_Iterator_YieldBreak() { var src1 = "class C { IEnumerable<int> M() { F(); yield break; } }"; var src2 = "class C { IEnumerable<int> M() { G(); yield break; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); VerifyPreserveLocalVariables(edits, preserveLocalVariables: true); } [WorkItem(1087305, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087305")] [Fact] public void MethodUpdate_LabeledStatement() { var src1 = @" class C { static void Main(string[] args) { goto Label1; Label1: { Console.WriteLine(1); } } }"; var src2 = @" class C { static void Main(string[] args) { goto Label1; Label1: { Console.WriteLine(2); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_LocalFunctionsParameterRefnessInBody() { var src1 = @"class C { public void M(int a) { void f(ref int b) => b = 1; } }"; var src2 = @"class C { public void M(int a) { void f(out int b) => b = 1; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public void M(int a) { void f(ref int b) => b = 1; }]@10 -> [public void M(int a) { void f(out int b) => b = 1; }]@10"); } [Fact] public void MethodUpdate_LambdaParameterRefnessInBody() { var src1 = @"class C { public void M(int a) { f((ref int b) => b = 1); } }"; var src2 = @"class C { public void M(int a) { f((out int b) => b = 1); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public void M(int a) { f((ref int b) => b = 1); }]@10 -> [public void M(int a) { f((out int b) => b = 1); }]@10"); } [Fact] public void Method_ReadOnlyRef_Parameter_InsertWhole() { var src1 = "class Test { }"; var src2 = "class Test { int M(in int b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [int M(in int b) => throw null;]@13", "Insert [(in int b)]@18", "Insert [in int b]@19"); edits.VerifyRudeDiagnostics(); } [Fact] public void Method_ReadOnlyRef_Parameter_InsertParameter() { var src1 = "class Test { int M() => throw null; }"; var src2 = "class Test { int M(in int b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [in int b]@19"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "in int b", FeaturesResources.parameter)); } [Fact] public void Method_ReadOnlyRef_Parameter_Update() { var src1 = "class Test { int M(int b) => throw null; }"; var src2 = "class Test { int M(in int b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int b]@19 -> [in int b]@19"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "in int b", FeaturesResources.parameter)); } [Fact] public void Method_ReadOnlyRef_ReturnType_Insert() { var src1 = "class Test { }"; var src2 = "class Test { ref readonly int M() => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [ref readonly int M() => throw null;]@13", "Insert [()]@31"); edits.VerifyRudeDiagnostics(); } [Fact] public void Method_ReadOnlyRef_ReturnType_Update() { var src1 = "class Test { int M() => throw null; }"; var src2 = "class Test { ref readonly int M() => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int M() => throw null;]@13 -> [ref readonly int M() => throw null;]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "ref readonly int M()", FeaturesResources.method)); } [Fact] public void Method_ImplementingInterface_Add() { var src1 = @" using System; public interface ISample { string Get(); } public interface IConflict { string Get(); } public class BaseClass : ISample { public virtual string Get() => string.Empty; } public class SubClass : BaseClass, IConflict { public override string Get() => string.Empty; } "; var src2 = @" using System; public interface ISample { string Get(); } public interface IConflict { string Get(); } public class BaseClass : ISample { public virtual string Get() => string.Empty; } public class SubClass : BaseClass, IConflict { public override string Get() => string.Empty; string IConflict.Get() => String.Empty; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [string IConflict.Get() => String.Empty;]@325", "Insert [()]@345"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertMethodWithExplicitInterfaceSpecifier, "string IConflict.Get()", FeaturesResources.method)); } [Fact] public void Method_Partial_DeleteInsert_DefinitionPart() { var srcA1 = "partial class C { partial void F(); }"; var srcB1 = "partial class C { partial void F() { } }"; var srcC1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { partial void F() { } }"; var srcC2 = "partial class C { partial void F(); }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults(), DocumentResults(), }); } [Fact] public void Method_Partial_DeleteInsert_ImplementationPart() { var srcA1 = "partial class C { partial void F(); }"; var srcB1 = "partial class C { partial void F() { } }"; var srcC1 = "partial class C { }"; var srcA2 = "partial class C { partial void F(); }"; var srcB2 = "partial class C { }"; var srcC2 = "partial class C { partial void F() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F").PartialImplementationPart) }), }); } [Fact, WorkItem(51011, "https://github.com/dotnet/roslyn/issues/51011")] public void Method_Partial_Swap_ImplementationAndDefinitionParts() { var srcA1 = "partial class C { partial void F(); }"; var srcB1 = "partial class C { partial void F() { } }"; var srcA2 = "partial class C { partial void F() { } }"; var srcB2 = "partial class C { partial void F(); }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F").PartialImplementationPart) }), DocumentResults(), }); } [Fact] public void Method_Partial_DeleteImplementation() { var srcA1 = "partial class C { partial void F(); }"; var srcB1 = "partial class C { partial void F() { } }"; var srcA2 = "partial class C { partial void F(); }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial class C", DeletedSymbolDisplay(FeaturesResources.method, "F()")) }) }); } [Fact] public void Method_Partial_DeleteBoth() { var srcA1 = "partial class C { partial void F(); }"; var srcB1 = "partial class C { partial void F() { } }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial class C", DeletedSymbolDisplay(FeaturesResources.method, "F()")) }) }); } [Fact] public void Method_Partial_DeleteInsertBoth() { var srcA1 = "partial class C { partial void F(); }"; var srcB1 = "partial class C { partial void F() { } }"; var srcC1 = "partial class C { }"; var srcD1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { }"; var srcC2 = "partial class C { partial void F(); }"; var srcD2 = "partial class C { partial void F() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2), GetTopEdits(srcD1, srcD2) }, new[] { DocumentResults(), DocumentResults(), DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F").PartialImplementationPart) }) }); } [Fact] public void Method_Partial_Insert() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { partial void F(); }"; var srcB2 = "partial class C { partial void F() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F").PartialImplementationPart) }), }); } [Fact] public void Method_Partial_Insert_Reloadable() { var srcA1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { }"; var srcB1 = "partial class C { }"; var srcA2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { partial void F(); }"; var srcB2 = "partial class C { partial void F() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C") }), }); } #endregion #region Operators [Theory] [InlineData("implicit", "explicit")] [InlineData("explicit", "implicit")] public void Operator_Modifiers_Update(string oldModifiers, string newModifiers) { var src1 = "class C { public static " + oldModifiers + " operator int (C c) => 0; }"; var src2 = "class C { public static " + newModifiers + " operator int (C c) => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [public static " + oldModifiers + " operator int (C c) => 0;]@10 -> [public static " + newModifiers + " operator int (C c) => 0;]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public static " + newModifiers + " operator int (C c)", CSharpFeaturesResources.conversion_operator)); } [Fact] public void Operator_Modifiers_Update_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { public static implicit operator int (C c) => 0; }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { public static explicit operator int (C c) => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Operator_Conversion_ExternModifiers_Add() { var src1 = "class C { public static implicit operator bool (C c) => default; }"; var src2 = "class C { extern public static implicit operator bool (C c); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "extern public static implicit operator bool (C c)", CSharpFeaturesResources.conversion_operator)); } [Fact] public void Operator_Conversion_ExternModifiers_Remove() { var src1 = "class C { extern public static implicit operator bool (C c); }"; var src2 = "class C { public static implicit operator bool (C c) => default; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public static implicit operator bool (C c)", CSharpFeaturesResources.conversion_operator)); } [Fact] public void OperatorInsert() { var src1 = @" class C { } "; var src2 = @" class C { public static implicit operator bool (C c) { return false; } public static C operator +(C c, C d) { return c; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertOperator, "public static implicit operator bool (C c)", CSharpFeaturesResources.conversion_operator), Diagnostic(RudeEditKind.InsertOperator, "public static C operator +(C c, C d)", FeaturesResources.operator_)); } [Fact] public void OperatorDelete() { var src1 = @" class C { public static implicit operator bool (C c) { return false; } public static C operator +(C c, C d) { return c; } } "; var src2 = @" class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(CSharpFeaturesResources.conversion_operator, "implicit operator bool(C c)")), Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.operator_, "operator +(C c, C d)"))); } [Fact] public void OperatorInsertDelete() { var srcA1 = @" partial class C { public static implicit operator bool (C c) => false; } "; var srcB1 = @" partial class C { public static C operator +(C c, C d) => c; } "; var srcA2 = srcB1; var srcB2 = srcA1; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("op_Addition")) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("op_Implicit")) }), }); } [Fact] public void OperatorUpdate() { var src1 = @" class C { public static implicit operator bool (C c) { return false; } public static C operator +(C c, C d) { return c; } } "; var src2 = @" class C { public static implicit operator bool (C c) { return true; } public static C operator +(C c, C d) { return d; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Implicit")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Addition")), }); } [Fact] public void OperatorWithExpressionBody_Update() { var src1 = @" class C { public static implicit operator bool (C c) => false; public static C operator +(C c, C d) => c; } "; var src2 = @" class C { public static implicit operator bool (C c) => true; public static C operator +(C c, C d) => d; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Implicit")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Addition")), }); } [Fact] public void OperatorWithExpressionBody_ToBlockBody() { var src1 = "class C { public static C operator +(C c, C d) => d; }"; var src2 = "class C { public static C operator +(C c, C d) { return c; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [public static C operator +(C c, C d) => d;]@10 -> [public static C operator +(C c, C d) { return c; }]@10"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Addition")) }); } [Fact] public void OperatorWithBlockBody_ToExpressionBody() { var src1 = "class C { public static C operator +(C c, C d) { return c; } }"; var src2 = "class C { public static C operator +(C c, C d) => d; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [public static C operator +(C c, C d) { return c; }]@10 -> [public static C operator +(C c, C d) => d;]@10"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Addition")) }); } [Fact] public void OperatorReorder1() { var src1 = @" class C { public static implicit operator bool (C c) { return false; } public static implicit operator int (C c) { return 1; } } "; var src2 = @" class C { public static implicit operator int (C c) { return 1; } public static implicit operator bool (C c) { return false; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [public static implicit operator int (C c) { return 1; }]@84 -> @18"); edits.VerifyRudeDiagnostics(); } [Fact] public void OperatorReorder2() { var src1 = @" class C { public static C operator +(C c, C d) { return c; } public static C operator -(C c, C d) { return d; } } "; var src2 = @" class C { public static C operator -(C c, C d) { return d; } public static C operator +(C c, C d) { return c; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [public static C operator -(C c, C d) { return d; }]@74 -> @18"); edits.VerifyRudeDiagnostics(); } [Fact] public void Operator_ReadOnlyRef_Parameter_InsertWhole() { var src1 = "class Test { }"; var src2 = "class Test { public static bool operator !(in Test b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [public static bool operator !(in Test b) => throw null;]@13", "Insert [(in Test b)]@42", "Insert [in Test b]@43"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertOperator, "public static bool operator !(in Test b)", FeaturesResources.operator_)); } [Fact] public void Operator_ReadOnlyRef_Parameter_Update() { var src1 = "class Test { public static bool operator !(Test b) => throw null; }"; var src2 = "class Test { public static bool operator !(in Test b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Test b]@43 -> [in Test b]@43"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "in Test b", FeaturesResources.parameter)); } #endregion #region Constructor, Destructor [Fact] public void Constructor_Parameter_AddAttribute() { var src1 = @" class C { private int x = 1; public C(int a) { } }"; var src2 = @" class C { private int x = 2; public C([System.Obsolete]int a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [x = 1]@30 -> [x = 2]@30", "Update [int a]@53 -> [[System.Obsolete]int a]@53"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C..ctor")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] [WorkItem(2068, "https://github.com/dotnet/roslyn/issues/2068")] public void Constructor_ExternModifier_Add() { var src1 = "class C { }"; var src2 = "class C { public extern C(); }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [public extern C();]@10", "Insert [()]@25"); // This can be allowed as the compiler generates an empty constructor, but it's not worth the complexity. edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public extern C()", FeaturesResources.constructor)); } [Fact] public void ConstructorInitializer_Update1() { var src1 = @" class C { public C(int a) : base(a) { } }"; var src2 = @" class C { public C(int a) : base(a + 1) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public C(int a) : base(a) { }]@18 -> [public C(int a) : base(a + 1) { }]@18"); edits.VerifyRudeDiagnostics(); } [Fact] public void ConstructorInitializer_Update2() { var src1 = @" class C<T> { public C(int a) : base(a) { } }"; var src2 = @" class C<T> { public C(int a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public C(int a) : base(a) { }]@21 -> [public C(int a) { }]@21"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.GenericTypeUpdate, "public C(int a)")); } [Fact] public void ConstructorInitializer_Update3() { var src1 = @" class C { public C(int a) { } }"; var src2 = @" class C { public C(int a) : base(a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public C(int a) { }]@18 -> [public C(int a) : base(a) { }]@18"); edits.VerifyRudeDiagnostics(); } [Fact] public void ConstructorInitializer_Update4() { var src1 = @" class C<T> { public C(int a) : base(a) { } }"; var src2 = @" class C<T> { public C(int a) : base(a + 1) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public C(int a) : base(a) { }]@21 -> [public C(int a) : base(a + 1) { }]@21"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.GenericTypeUpdate, "public C(int a)")); } [WorkItem(743552, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/743552")] [Fact] public void ConstructorUpdate_AddParameter() { var src1 = @" class C { public C(int a) { } }"; var src2 = @" class C { public C(int a, int b) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int a)]@26 -> [(int a, int b)]@26", "Insert [int b]@34"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "int b", FeaturesResources.parameter)); } [Fact] public void DestructorDelete() { var src1 = @"class B { ~B() { } }"; var src2 = @"class B { }"; var expectedEdit1 = @"Delete [~B() { }]@10"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(expectedEdit1); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class B", DeletedSymbolDisplay(CSharpFeaturesResources.destructor, "~B()"))); } [Fact] public void DestructorDelete_InsertConstructor() { var src1 = @"class B { ~B() { } }"; var src2 = @"class B { B() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [B() { }]@10", "Insert [()]@11", "Delete [~B() { }]@10"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "B()", FeaturesResources.constructor), Diagnostic(RudeEditKind.Delete, "class B", DeletedSymbolDisplay(CSharpFeaturesResources.destructor, "~B()"))); } [Fact] [WorkItem(789577, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/789577")] public void ConstructorUpdate_AnonymousTypeInFieldInitializer() { var src1 = "class C { int a = F(new { A = 1, B = 2 }); C() { x = 1; } }"; var src2 = "class C { int a = F(new { A = 1, B = 2 }); C() { x = 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Constructor_Static_Delete() { var src1 = "class C { static C() { } }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.static_constructor, "C()"))); } [Fact] public void Constructor_Static_Delete_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { static C() { } }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Constructor_Static_Insert() { var src1 = "class C { }"; var src2 = "class C { static C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single()) }); } [Fact] public void InstanceCtorDelete_Public() { var src1 = "class C { public C() { } }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Theory] [InlineData("")] [InlineData("private")] [InlineData("protected")] [InlineData("internal")] [InlineData("private protected")] [InlineData("protected internal")] public void InstanceCtorDelete_NonPublic(string accessibility) { var src1 = "class C { [System.Obsolete] " + accessibility + " C() { } }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()")), Diagnostic(RudeEditKind.ChangingAccessibility, "class C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()"))); } [Fact] public void InstanceCtorDelete_Public_PartialWithInitializerUpdate() { var srcA1 = "partial class C { public C() { } }"; var srcB1 = "partial class C { int x = 1; }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int x = 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }) }); } [Fact] public void InstanceCtorInsert_Public_Implicit() { var src1 = "class C { }"; var src2 = "class C { public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void InstanceCtorInsert_Partial_Public_Implicit() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { public C() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // no change in document A DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void InstanceCtorInsert_Public_NoImplicit() { var src1 = "class C { public C(int a) { } }"; var src2 = "class C { public C(int a) { } public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, expectedSemanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(c => c.Parameters.IsEmpty)) }); } [Fact] public void InstanceCtorInsert_Partial_Public_NoImplicit() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { public C(int a) { } }"; var srcA2 = "partial class C { public C() { } }"; var srcB2 = "partial class C { public C(int a) { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(c => c.Parameters.IsEmpty)) }), // no change in document B DocumentResults(), }); } [Fact] public void InstanceCtorInsert_Private_Implicit1() { var src1 = "class C { }"; var src2 = "class C { private C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "private C()", FeaturesResources.constructor)); } [Fact] public void InstanceCtorInsert_Private_Implicit2() { var src1 = "class C { }"; var src2 = "class C { C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "C()", FeaturesResources.constructor)); } [Fact] public void InstanceCtorInsert_Protected_PublicImplicit() { var src1 = "class C { }"; var src2 = "class C { protected C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "protected C()", FeaturesResources.constructor)); } [Fact] public void InstanceCtorInsert_Internal_PublicImplicit() { var src1 = "class C { }"; var src2 = "class C { internal C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "internal C()", FeaturesResources.constructor)); } [Fact] public void InstanceCtorInsert_Internal_ProtectedImplicit() { var src1 = "abstract class C { }"; var src2 = "abstract class C { internal C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "internal C()", FeaturesResources.constructor)); } [Fact] public void InstanceCtorUpdate_ProtectedImplicit() { var src1 = "abstract class C { }"; var src2 = "abstract class C { protected C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void InstanceCtorInsert_Private_NoImplicit() { var src1 = "class C { public C(int a) { } }"; var src2 = "class C { public C(int a) { } private C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C") .InstanceConstructors.Single(ctor => ctor.DeclaredAccessibility == Accessibility.Private)) }); } [Fact] public void InstanceCtorInsert_Internal_NoImplicit() { var src1 = "class C { public C(int a) { } }"; var src2 = "class C { public C(int a) { } internal C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void InstanceCtorInsert_Protected_NoImplicit() { var src1 = "class C { public C(int a) { } }"; var src2 = "class C { public C(int a) { } protected C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void InstanceCtorInsert_InternalProtected_NoImplicit() { var src1 = "class C { public C(int a) { } }"; var src2 = "class C { public C(int a) { } internal protected C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void StaticCtor_Partial_DeleteInsert() { var srcA1 = "partial class C { static C() { } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { static C() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void InstanceCtor_Partial_DeletePrivateInsertPrivate() { var srcA1 = "partial class C { C() { } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { C() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void InstanceCtor_Partial_DeletePublicInsertPublic() { var srcA1 = "partial class C { public C() { } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { public C() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void InstanceCtor_Partial_DeletePrivateInsertPublic() { var srcA1 = "partial class C { C() { } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { public C() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // delete of the constructor in partial part will be reported as rude edit in the other document where it was inserted back with changed accessibility DocumentResults( semanticEdits: NoSemanticEdits), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.ChangingAccessibility, "public C()", FeaturesResources.constructor) }), }); } [Fact] public void StaticCtor_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { static C() { } }"; var srcA2 = "partial class C { static C() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_InsertPublicDeletePublic() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { public C() { } }"; var srcA2 = "partial class C { public C() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_InsertPrivateDeletePrivate() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { private C() { } }"; var srcA2 = "partial class C { private C() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_DeleteInternalInsertInternal() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { internal C() { } }"; var srcA2 = "partial class C { internal C() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_InsertInternalDeleteInternal_WithBody() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { internal C() { } }"; var srcA2 = "partial class C { internal C() { Console.WriteLine(1); } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_InsertPublicDeletePrivate() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { private C() { } }"; var srcA2 = "partial class C { public C() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.ChangingAccessibility, "public C()", FeaturesResources.constructor) }), // delete of the constructor in partial part will be reported as rude in the the other document where it was inserted with changed accessibility DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_InsertInternalDeletePrivate() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { private C() { } }"; var srcA2 = "partial class C { internal C() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.ChangingAccessibility, "internal C()", FeaturesResources.constructor) }), DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_Update_LambdaInInitializer1() { var src1 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); public C() { F(<N:0.2>c => c + 1</N:0.2>); } } "; var src2 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); public C() { F(<N:0.2>c => c + 2</N:0.2>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void InstanceCtor_Partial_Update_LambdaInInitializer_Trivia1() { var src1 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); public C() { F(<N:0.2>c => c + 1</N:0.2>); } } "; var src2 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); /*new trivia*/public C() { F(<N:0.2>c => c + 1</N:0.2>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void InstanceCtor_Partial_Update_LambdaInInitializer_ExplicitInterfaceImpl1() { var src1 = @" using System; public interface I { int B { get; } } public interface J { int B { get; } } partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C : I, J { int I.B { get; } = F(<N:0.1>ib => ib + 1</N:0.1>); int J.B { get; } = F(<N:0.2>jb => jb + 1</N:0.2>); public C() { F(<N:0.3>c => c + 1</N:0.3>); } } "; var src2 = @" using System; public interface I { int B { get; } } public interface J { int B { get; } } partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C : I, J { int I.B { get; } = F(<N:0.1>ib => ib + 1</N:0.1>); int J.B { get; } = F(<N:0.2>jb => jb + 1</N:0.2>); public C() { F(<N:0.3>c => c + 2</N:0.3>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact, WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")] public void InstanceCtor_Partial_Insert_Parameterless_LambdaInInitializer1() { var src1 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); } "; var src2 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); public C() // new ctor { F(c => c + 1); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, "public C()")); // TODO: //var syntaxMap = GetSyntaxMap(src1, src2); //edits.VerifySemantics( // ActiveStatementsDescription.Empty, // new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact, WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")] public void InstanceCtor_Partial_Insert_WithParameters_LambdaInInitializer1() { var src1 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); } "; var src2 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); public C(int x) // new ctor { F(c => c + 1); } } "; var edits = GetTopEdits(src1, src2); _ = GetSyntaxMap(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, "public C(int x)")); // TODO: bug https://github.com/dotnet/roslyn/issues/2504 //edits.VerifySemantics( // ActiveStatementsDescription.Empty, // new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<NamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void InstanceCtor_Partial_Explicit_Update() { var srcA1 = @" using System; partial class C { C(int arg) => Console.WriteLine(0); C(bool arg) => Console.WriteLine(1); } "; var srcB1 = @" using System; partial class C { int a <N:0.0>= 1</N:0.0>; C(uint arg) => Console.WriteLine(2); } "; var srcA2 = @" using System; partial class C { C(int arg) => Console.WriteLine(0); C(bool arg) => Console.WriteLine(1); } "; var srcB2 = @" using System; partial class C { int a <N:0.0>= 2</N:0.0>; // updated field initializer C(uint arg) => Console.WriteLine(2); C(byte arg) => Console.WriteLine(3); // new ctor } "; var syntaxMapB = GetSyntaxMap(srcB1, srcB2)[0]; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // No changes in document A DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Single().Type.Name == "Int32"), partialType: "C", syntaxMap: syntaxMapB), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Single().Type.Name == "Boolean"), partialType: "C", syntaxMap: syntaxMapB), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Single().Type.Name == "UInt32"), partialType: "C", syntaxMap: syntaxMapB), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Single().Type.Name == "Byte"), syntaxMap: null), }) }); } [Fact] public void InstanceCtor_Partial_Explicit_Update_SemanticError() { var srcA1 = @" using System; partial class C { C(int arg) => Console.WriteLine(0); C(int arg) => Console.WriteLine(1); } "; var srcB1 = @" using System; partial class C { int a = 1; } "; var srcA2 = @" using System; partial class C { C(int arg) => Console.WriteLine(0); C(int arg) => Console.WriteLine(1); } "; var srcB2 = @" using System; partial class C { int a = 2; C(int arg) => Console.WriteLine(2); } "; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // No changes in document A DocumentResults(), // The actual edits do not matter since there are semantic errors in the compilation. // We just should not crash. DocumentResults(diagnostics: Array.Empty<RudeEditDiagnosticDescription>()) }); } [Fact] public void InstanceCtor_Partial_Implicit_Update() { var srcA1 = "partial class C { int F = 1; }"; var srcB1 = "partial class C { int G = 1; }"; var srcA2 = "partial class C { int F = 2; }"; var srcB2 = "partial class C { int G = 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void ParameterlessConstructor_SemanticError_Delete1() { var src1 = @" class C { D() {} } "; var src2 = @" class C { } "; var edits = GetTopEdits(src1, src2); // The compiler interprets D() as a constructor declaration. edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "class C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()"))); } [Fact] public void Constructor_SemanticError_Partial() { var src1 = @" partial class C { partial void C(int x); } partial class C { partial void C(int x) { System.Console.WriteLine(1); } } "; var src2 = @" partial class C { partial void C(int x); } partial class C { partial void C(int x) { System.Console.WriteLine(2); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(ActiveStatementsDescription.Empty, expectedSemanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("C").PartialImplementationPart) }); } [Fact] public void PartialDeclaration_Delete() { var srcA1 = "partial class C { public C() { } void F() { } }"; var srcB1 = "partial class C { int x = 1; }"; var srcA2 = ""; var srcB2 = "partial class C { int x = 2; void F() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void PartialDeclaration_Insert() { var srcA1 = ""; var srcB1 = "partial class C { int x = 1; void F() { } }"; var srcA2 = "partial class C { public C() { } void F() { } }"; var srcB2 = "partial class C { int x = 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void PartialDeclaration_Insert_Reloadable() { var srcA1 = ""; var srcB1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { int x = 1; void F() { } }"; var srcA2 = "partial class C { public C() { } void F() { } }"; var srcB2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { int x = 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C") }), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C") }), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Constructor_BlockBodyToExpressionBody() { var src1 = @" public class C { private int _value; public C(int value) { _value = value; } } "; var src2 = @" public class C { private int _value; public C(int value) => _value = value; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [public C(int value) { _value = value; }]@52 -> [public C(int value) => _value = value;]@52"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void ConstructorWithInitializer_BlockBodyToExpressionBody() { var src1 = @" public class B { B(int value) {} } public class C : B { private int _value; public C(int value) : base(value) { _value = value; } } "; var src2 = @" public class B { B(int value) {} } public class C : B { private int _value; public C(int value) : base(value) => _value = value; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [public C(int value) : base(value) { _value = value; }]@90 -> [public C(int value) : base(value) => _value = value;]@90"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Constructor_ExpressionBodyToBlockBody() { var src1 = @" public class C { private int _value; public C(int value) => _value = value; } "; var src2 = @" public class C { private int _value; public C(int value) { _value = value; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(@"Update [public C(int value) => _value = value;]@52 -> [public C(int value) { _value = value; }]@52"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void ConstructorWithInitializer_ExpressionBodyToBlockBody() { var src1 = @" public class B { B(int value) {} } public class C : B { private int _value; public C(int value) : base(value) => _value = value; } "; var src2 = @" public class B { B(int value) {} } public class C : B { private int _value; public C(int value) : base(value) { _value = value; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(@"Update [public C(int value) : base(value) => _value = value;]@90 -> [public C(int value) : base(value) { _value = value; }]@90"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Destructor_BlockBodyToExpressionBody() { var src1 = @" public class C { ~C() { Console.WriteLine(0); } } "; var src2 = @" public class C { ~C() => Console.WriteLine(0); } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [~C() { Console.WriteLine(0); }]@25 -> [~C() => Console.WriteLine(0);]@25"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Finalize"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Destructor_ExpressionBodyToBlockBody() { var src1 = @" public class C { ~C() => Console.WriteLine(0); } "; var src2 = @" public class C { ~C() { Console.WriteLine(0); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [~C() => Console.WriteLine(0);]@25 -> [~C() { Console.WriteLine(0); }]@25"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Finalize"), preserveLocalVariables: false) }); } [Fact] public void Constructor_ReadOnlyRef_Parameter_InsertWhole() { var src1 = "class Test { }"; var src2 = "class Test { Test(in int b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [Test(in int b) => throw null;]@13", "Insert [(in int b)]@17", "Insert [in int b]@18"); edits.VerifyRudeDiagnostics(); } [Fact] public void Constructor_ReadOnlyRef_Parameter_InsertParameter() { var src1 = "class Test { Test() => throw null; }"; var src2 = "class Test { Test(in int b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [in int b]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "in int b", FeaturesResources.parameter)); } [Fact] public void Constructor_ReadOnlyRef_Parameter_Update() { var src1 = "class Test { Test(int b) => throw null; }"; var src2 = "class Test { Test(in int b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int b]@18 -> [in int b]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "in int b", FeaturesResources.parameter)); } #endregion #region Fields and Properties with Initializers [Fact] public void FieldInitializer_Update1() { var src1 = "class C { int a = 0; }"; var src2 = "class C { int a = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 0]@14 -> [a = 1]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializer_Update1() { var src1 = "class C { int a { get; } = 0; }"; var src2 = "class C { int a { get; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a { get; } = 0;]@10 -> [int a { get; } = 1;]@10"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializer_Update2() { var src1 = "class C { int a = 0; }"; var src2 = "class C { int a; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 0]@14 -> [a]@14"); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyInitializer_Update2() { var src1 = "class C { int a { get; } = 0; }"; var src2 = "class C { int a { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a { get; } = 0;]@10 -> [int a { get { return 1; } }]@10", "Update [get;]@18 -> [get { return 1; }]@18"); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.a").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), preserveLocalVariables: true)); } [Fact] public void PropertyInitializer_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int a { get; } = 0; }"; var srcA2 = "partial class C { int a { get { return 1; } } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.a").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults() }); } [Fact] public void FieldInitializer_Update3() { var src1 = "class C { int a; }"; var src2 = "class C { int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@14 -> [a = 0]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializer_Update3() { var src1 = "class C { int a { get { return 1; } } }"; var src2 = "class C { int a { get; } = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a { get { return 1; } }]@10 -> [int a { get; } = 0;]@10", "Update [get { return 1; }]@18 -> [get;]@18"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.a").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_StaticCtorUpdate1() { var src1 = "class C { static int a; static C() { } }"; var src2 = "class C { static int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@21 -> [a = 0]@21", "Delete [static C() { }]@24", "Delete [()]@32"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_StaticCtorUpdate1() { var src1 = "class C { static int a { get; } = 1; static C() { } }"; var src2 = "class C { static int a { get; } = 2;}"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_InstanceCtorUpdate_Private() { var src1 = "class C { int a; [System.Obsolete]C() { } }"; var src2 = "class C { int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()")), Diagnostic(RudeEditKind.ChangingAccessibility, "class C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()"))); } [Fact] public void PropertyInitializerUpdate_InstanceCtorUpdate_Private() { var src1 = "class C { int a { get; } = 1; C() { } }"; var src2 = "class C { int a { get; } = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "class C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()"))); } [Fact] public void FieldInitializerUpdate_InstanceCtorUpdate_Public() { var src1 = "class C { int a; public C() { } }"; var src2 = "class C { int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_InstanceCtorUpdate_Public() { var src1 = "class C { int a { get; } = 1; public C() { } }"; var src2 = "class C { int a { get; } = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_StaticCtorUpdate2() { var src1 = "class C { static int a; static C() { } }"; var src2 = "class C { static int a = 0; static C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@21 -> [a = 0]@21"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_StaticCtorUpdate2() { var src1 = "class C { static int a { get; } = 1; static C() { } }"; var src2 = "class C { static int a { get; } = 2; static C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_InstanceCtorUpdate2() { var src1 = "class C { int a; public C() { } }"; var src2 = "class C { int a = 0; public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@14 -> [a = 0]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_InstanceCtorUpdate2() { var src1 = "class C { int a { get; } = 1; public C() { } }"; var src2 = "class C { int a { get; } = 2; public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_InstanceCtorUpdate3() { var src1 = "class C { int a; }"; var src2 = "class C { int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@14 -> [a = 0]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_InstanceCtorUpdate3() { var src1 = "class C { int a { get; } = 1; }"; var src2 = "class C { int a { get; } = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_InstanceCtorUpdate4() { var src1 = "class C { int a = 0; }"; var src2 = "class C { int a; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 0]@14 -> [a]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_InstanceCtorUpdate5() { var src1 = "class C { int a; private C(int a) { } private C(bool a) { } }"; var src2 = "class C { int a = 0; private C(int a) { } private C(bool a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@14 -> [a = 0]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(int)"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(bool)"), preserveLocalVariables: true), }); } [Fact] public void PropertyInitializerUpdate_InstanceCtorUpdate5() { var src1 = "class C { int a { get; } = 1; private C(int a) { } private C(bool a) { } }"; var src2 = "class C { int a { get; } = 10000; private C(int a) { } private C(bool a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(int)"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(bool)"), preserveLocalVariables: true), }); } [Fact] public void FieldInitializerUpdate_InstanceCtorUpdate6() { var src1 = "class C { int a; private C(int a) : this(true) { } private C(bool a) { } }"; var src2 = "class C { int a = 0; private C(int a) : this(true) { } private C(bool a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@14 -> [a = 0]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(bool)"), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_StaticCtorInsertImplicit() { var src1 = "class C { static int a; }"; var src2 = "class C { static int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@21 -> [a = 0]@21"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single()) }); } [Fact] public void FieldInitializerUpdate_StaticCtorInsertExplicit() { var src1 = "class C { static int a; }"; var src2 = "class C { static int a = 0; static C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [static C() { }]@28", "Insert [()]@36", "Update [a]@21 -> [a = 0]@21"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single()) }); } [Fact] public void FieldInitializerUpdate_InstanceCtorInsertExplicit() { var src1 = "class C { int a; }"; var src2 = "class C { int a = 0; public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_InstanceCtorInsertExplicit() { var src1 = "class C { int a { get; } = 1; }"; var src2 = "class C { int a { get; } = 2; public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_GenericType() { var src1 = "class C<T> { int a = 1; }"; var src2 = "class C<T> { int a = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 1]@17 -> [a = 2]@17"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.GenericTypeUpdate, "a = 2"), Diagnostic(RudeEditKind.GenericTypeUpdate, "class C<T>")); } [Fact] public void PropertyInitializerUpdate_GenericType() { var src1 = "class C<T> { int a { get; } = 1; }"; var src2 = "class C<T> { int a { get; } = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.GenericTypeUpdate, "int a"), Diagnostic(RudeEditKind.GenericTypeUpdate, "class C<T>")); } [Fact] public void FieldInitializerUpdate_StackAllocInConstructor() { var src1 = "unsafe class C { int a = 1; public C() { int* a = stackalloc int[10]; } }"; var src2 = "unsafe class C { int a = 2; public C() { int* a = stackalloc int[10]; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 1]@21 -> [a = 2]@21"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", FeaturesResources.constructor)); } [Fact] [WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void FieldInitializerUpdate_SwitchExpressionInConstructor() { var src1 = "class C { int a = 1; public C() { var b = a switch { 0 => 0, _ => 1 }; } }"; var src2 = "class C { int a = 2; public C() { var b = a switch { 0 => 0, _ => 1 }; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void PropertyInitializerUpdate_StackAllocInConstructor1() { var src1 = "unsafe class C { int a { get; } = 1; public C() { int* a = stackalloc int[10]; } }"; var src2 = "unsafe class C { int a { get; } = 2; public C() { int* a = stackalloc int[10]; } }"; var edits = GetTopEdits(src1, src2); // TODO (tomat): diagnostic should point to the property initializer edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", FeaturesResources.constructor)); } [Fact] public void PropertyInitializerUpdate_StackAllocInConstructor2() { var src1 = "unsafe class C { int a { get; } = 1; public C() : this(1) { int* a = stackalloc int[10]; } public C(int a) { } }"; var src2 = "unsafe class C { int a { get; } = 2; public C() : this(1) { int* a = stackalloc int[10]; } public C(int a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void PropertyInitializerUpdate_StackAllocInConstructor3() { var src1 = "unsafe class C { int a { get; } = 1; public C() { } public C(int b) { int* a = stackalloc int[10]; } }"; var src2 = "unsafe class C { int a { get; } = 2; public C() { } public C(int b) { int* a = stackalloc int[10]; } }"; var edits = GetTopEdits(src1, src2); // TODO (tomat): diagnostic should point to the property initializer edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", FeaturesResources.constructor)); } [Fact] [WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void PropertyInitializerUpdate_SwitchExpressionInConstructor1() { var src1 = "class C { int a { get; } = 1; public C() { var b = a switch { 0 => 0, _ => 1 }; } }"; var src2 = "class C { int a { get; } = 2; public C() { var b = a switch { 0 => 0, _ => 1 }; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] [WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void PropertyInitializerUpdate_SwitchExpressionInConstructor2() { var src1 = "class C { int a { get; } = 1; public C() : this(1) { var b = a switch { 0 => 0, _ => 1 }; } public C(int a) { } }"; var src2 = "class C { int a { get; } = 2; public C() : this(1) { var b = a switch { 0 => 0, _ => 1 }; } public C(int a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] [WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void PropertyInitializerUpdate_SwitchExpressionInConstructor3() { var src1 = "class C { int a { get; } = 1; public C() { } public C(int b) { var b = a switch { 0 => 0, _ => 1 }; } }"; var src2 = "class C { int a { get; } = 2; public C() { } public C(int b) { var b = a switch { 0 => 0, _ => 1 }; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void FieldInitializerUpdate_LambdaInConstructor() { var src1 = "class C { int a = 1; public C() { F(() => {}); } static void F(System.Action a) {} }"; var src2 = "class C { int a = 2; public C() { F(() => {}); } static void F(System.Action a) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 1]@14 -> [a = 2]@14"); edits.VerifySemanticDiagnostics(); } [Fact] public void PropertyInitializerUpdate_LambdaInConstructor() { var src1 = "class C { int a { get; } = 1; public C() { F(() => {}); } static void F(System.Action a) {} }"; var src2 = "class C { int a { get; } = 2; public C() { F(() => {}); } static void F(System.Action a) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void FieldInitializerUpdate_QueryInConstructor() { var src1 = "using System.Linq; class C { int a = 1; public C() { F(from a in new[] {1,2,3} select a + 1); } static void F(System.Collections.Generic.IEnumerable<int> x) {} }"; var src2 = "using System.Linq; class C { int a = 2; public C() { F(from a in new[] {1,2,3} select a + 1); } static void F(System.Collections.Generic.IEnumerable<int> x) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 1]@33 -> [a = 2]@33"); edits.VerifySemanticDiagnostics(); } [Fact] public void PropertyInitializerUpdate_QueryInConstructor() { var src1 = "using System.Linq; class C { int a { get; } = 1; public C() { F(from a in new[] {1,2,3} select a + 1); } static void F(System.Collections.Generic.IEnumerable<int> x) {} }"; var src2 = "using System.Linq; class C { int a { get; } = 2; public C() { F(from a in new[] {1,2,3} select a + 1); } static void F(System.Collections.Generic.IEnumerable<int> x) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void FieldInitializerUpdate_AnonymousTypeInConstructor() { var src1 = "class C { int a = 1; C() { F(new { A = 1, B = 2 }); } static void F(object x) {} }"; var src2 = "class C { int a = 2; C() { F(new { A = 1, B = 2 }); } static void F(object x) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void PropertyInitializerUpdate_AnonymousTypeInConstructor() { var src1 = "class C { int a { get; } = 1; C() { F(new { A = 1, B = 2 }); } static void F(object x) {} }"; var src2 = "class C { int a { get; } = 2; C() { F(new { A = 1, B = 2 }); } static void F(object x) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void FieldInitializerUpdate_PartialTypeWithSingleDeclaration() { var src1 = "partial class C { int a = 1; }"; var src2 = "partial class C { int a = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 1]@22 -> [a = 2]@22"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_PartialTypeWithSingleDeclaration() { var src1 = "partial class C { int a { get; } = 1; }"; var src2 = "partial class C { int a { get; } = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_PartialTypeWithMultipleDeclarations() { var src1 = "partial class C { int a = 1; } partial class C { }"; var src2 = "partial class C { int a = 2; } partial class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 1]@22 -> [a = 2]@22"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_PartialTypeWithMultipleDeclarations() { var src1 = "partial class C { int a { get; } = 1; } partial class C { }"; var src2 = "partial class C { int a { get; } = 2; } partial class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_ParenthesizedLambda() { var src1 = "class C { int a = F(1, (x, y) => x + y); }"; var src2 = "class C { int a = F(2, (x, y) => x + y); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyInitializerUpdate_ParenthesizedLambda() { var src1 = "class C { int a { get; } = F(1, (x, y) => x + y); }"; var src2 = "class C { int a { get; } = F(2, (x, y) => x + y); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void FieldInitializerUpdate_SimpleLambda() { var src1 = "class C { int a = F(1, x => x); }"; var src2 = "class C { int a = F(2, x => x); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyInitializerUpdate_SimpleLambda() { var src1 = "class C { int a { get; } = F(1, x => x); }"; var src2 = "class C { int a { get; } = F(2, x => x); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void FieldInitializerUpdate_Query() { var src1 = "class C { int a = F(1, from goo in bar select baz); }"; var src2 = "class C { int a = F(2, from goo in bar select baz); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyInitializerUpdate_Query() { var src1 = "class C { int a { get; } = F(1, from goo in bar select baz); }"; var src2 = "class C { int a { get; } = F(2, from goo in bar select baz); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void FieldInitializerUpdate_AnonymousType() { var src1 = "class C { int a = F(1, new { A = 1, B = 2 }); }"; var src2 = "class C { int a = F(2, new { A = 1, B = 2 }); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyInitializerUpdate_AnonymousType() { var src1 = "class C { int a { get; } = F(1, new { A = 1, B = 2 }); }"; var src2 = "class C { int a { get; } = F(2, new { A = 1, B = 2 }); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void FieldInitializerUpdate_Lambdas_ImplicitCtor_EditInitializerWithLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 2</N:0.1>); } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_ImplicitCtor_EditInitializerWithoutLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = 1; int B = F(<N:0.0>b => b + 1</N:0.0>); } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = 2; int B = F(<N:0.0>b => b + 1</N:0.0>); } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_CtorIncludingInitializers_EditInitializerWithLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C() {} } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 2</N:0.1>); public C() {} } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_CtorIncludingInitializers_EditInitializerWithoutLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = 1; int B = F(<N:0.0>b => b + 1</N:0.0>); public C() {} } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = 2; int B = F(<N:0.0>b => b + 1</N:0.0>); public C() {} } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializers_EditInitializerWithLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) {} public C(bool b) {} } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 2</N:0.1>); public C(int a) {} public C(bool b) {} } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[0], syntaxMap[0]), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[1], syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializersContainingLambdas_EditInitializerWithLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(<N:0.3>d => d + 1</N:0.3>); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 2</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(<N:0.3>d => d + 1</N:0.3>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[0], syntaxMap[0]), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[1], syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializersContainingLambdas_EditInitializerWithLambda_Trivia1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(<N:0.3>d => d + 1</N:0.3>); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(<N:0.3>d => d + 1</N:0.3>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[0], syntaxMap[0]), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[1], syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializersContainingLambdas_EditConstructorWithLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(d => d + 1); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 2</N:0.2>); } public C(bool b) { F(d => d + 1); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Int32 a)"), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializersContainingLambdas_EditConstructorWithLambda_Trivia1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(d => d + 1); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(d => d + 1); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Int32 a)"), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializersContainingLambdas_EditConstructorWithoutLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(c => c + 1); } public C(bool b) { Console.WriteLine(1); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(c => c + 1); } public C(bool b) { Console.WriteLine(2); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Boolean b)"), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_EditConstructorNotIncludingInitializers() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(a => a + 1); int B = F(b => b + 1); public C(int a) { F(c => c + 1); } public C(bool b) : this(1) { Console.WriteLine(1); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(a => a + 1); int B = F(b => b + 1); public C(int a) { F(c => c + 1); } public C(bool b) : this(1) { Console.WriteLine(2); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Boolean b)")) }); } [Fact] public void FieldInitializerUpdate_Lambdas_RemoveCtorInitializer1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); unsafe public C(int a) { char* buffer = stackalloc char[16]; F(c => c + 1); } public C(bool b) : this(1) { Console.WriteLine(1); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); unsafe public C(int a) { char* buffer = stackalloc char[16]; F(c => c + 1); } public C(bool b) { Console.WriteLine(1); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Boolean b)"), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_AddCtorInitializer1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(a => a + 1); int B = F(b => b + 1); public C(int a) { F(c => c + 1); } public C(bool b) { Console.WriteLine(1); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(a => a + 1); int B = F(b => b + 1); public C(int a) { F(c => c + 1); } public C(bool b) : this(1) { Console.WriteLine(1); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Boolean b)")) }); } [Fact] public void FieldInitializerUpdate_Lambdas_UpdateBaseCtorInitializerWithLambdas1() { var src1 = @" using System; class B { public B(int a) { } } class C : B { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(bool b) : base(F(<N:0.2>c => c + 1</N:0.2>)) { F(<N:0.3>d => d + 1</N:0.3>); } } "; var src2 = @" using System; class B { public B(int a) { } } class C : B { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(bool b) : base(F(<N:0.2>c => c + 2</N:0.2>)) { F(<N:0.3>d => d + 1</N:0.3>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Boolean b)"), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_PartialDeclarationDelete_SingleDocument() { var src1 = @" partial class C { int x = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int y = F(<N:0.1>a => a + 10</N:0.1>); } partial class C { public C() { } static int F(Func<int, int> x) => 1; } "; var src2 = @" partial class C { int x = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int y = F(<N:0.1>a => a + 10</N:0.1>); static int F(Func<int, int> x) => 1; } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), syntaxMap[0]), }); } [Fact] public void FieldInitializerUpdate_ActiveStatements1() { var src1 = @" using System; class C { <AS:0>int A = <N:0.0>1</N:0.0>;</AS:0> int B = 1; public C(int a) { Console.WriteLine(1); } public C(bool b) { Console.WriteLine(1); } } "; var src2 = @" using System; class C { <AS:0>int A = <N:0.0>1</N:0.0>;</AS:0> int B = 2; public C(int a) { Console.WriteLine(1); } public C(bool b) { Console.WriteLine(1); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); var activeStatements = GetActiveStatements(src1, src2); edits.VerifySemantics( activeStatements, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[0], syntaxMap[0]), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[1], syntaxMap[0]), }); } [Fact] public void PropertyWithInitializer_SemanticError_Partial() { var src1 = @" partial class C { partial int P => 1; } partial class C { partial int P => 1; } "; var src2 = @" partial class C { partial int P => 1; } partial class C { partial int P => 2; public C() { } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(ActiveStatementsDescription.Empty, expectedSemanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => ((IPropertySymbol)c.GetMember<INamedTypeSymbol>("C").GetMembers("P").First()).GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void Field_Partial_DeleteInsert_InitializerRemoval() { var srcA1 = "partial class C { int F = 1; }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int F; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void Field_Partial_DeleteInsert_InitializerUpdate() { var srcA1 = "partial class C { int F = 1; }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int F = 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } #endregion #region Fields [Fact] public void Field_Rename() { var src1 = "class C { int a = 0; }"; var src2 = "class C { int b = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 0]@14 -> [b = 0]@14"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "b = 0", FeaturesResources.field)); } [Fact] public void Field_Kind_Update() { var src1 = "class C { Action a; }"; var src2 = "class C { event Action a; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Action a;]@10 -> [event Action a;]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.FieldKindUpdate, "event Action a", FeaturesResources.event_)); } [Theory] [InlineData("static")] [InlineData("volatile")] [InlineData("const")] public void Field_Modifiers_Update(string oldModifiers, string newModifiers = "") { if (oldModifiers != "") { oldModifiers += " "; } if (newModifiers != "") { newModifiers += " "; } var src1 = "class C { " + oldModifiers + "int F = 0; }"; var src2 = "class C { " + newModifiers + "int F = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [" + oldModifiers + "int F = 0;]@10 -> [" + newModifiers + "int F = 0;]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, newModifiers + "int F = 0", FeaturesResources.field)); } [Fact] public void Field_Modifier_Add_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int F; }"; var srcA2 = "partial class C { static int F; }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.ModifiersUpdate, "F", FeaturesResources.field) }), DocumentResults(), }); } [Fact] public void Field_Attribute_Add_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int F; }"; var srcA2 = "partial class C { [System.Obsolete]int F; }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")) }), DocumentResults(), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Field_FixedSize_Update() { var src1 = "struct S { public unsafe fixed byte a[1], b[2]; }"; var src2 = "struct S { public unsafe fixed byte a[2], b[3]; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a[1]]@36 -> [a[2]]@36", "Update [b[2]]@42 -> [b[3]]@42"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.FixedSizeFieldUpdate, "a[2]", FeaturesResources.field), Diagnostic(RudeEditKind.FixedSizeFieldUpdate, "b[3]", FeaturesResources.field)); } [WorkItem(1120407, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1120407")] [Fact] public void Field_Const_Update() { var src1 = "class C { const int x = 0; }"; var src2 = "class C { const int x = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [x = 0]@20 -> [x = 1]@20"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, "x = 1", FeaturesResources.const_field)); } [Fact] public void Field_Event_VariableDeclarator_Update() { var src1 = "class C { event Action a; }"; var src2 = "class C { event Action a = () => { }; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@23 -> [a = () => { }]@23"); edits.VerifyRudeDiagnostics(); } [Fact] public void Field_Reorder() { var src1 = "class C { int a = 0; int b = 1; int c = 2; }"; var src2 = "class C { int c = 2; int a = 0; int b = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [int c = 2;]@32 -> @10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "int c = 2", FeaturesResources.field)); } [Fact] public void Field_Insert() { var src1 = "class C { }"; var src2 = "class C { int a = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [int a = 1;]@10", "Insert [int a = 1]@10", "Insert [a = 1]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.a")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void Field_Insert_IntoStruct() { var src1 = @" struct S { public int a; public S(int z) { this = default(S); a = z; } } "; var src2 = @" struct S { public int a; private int b; private static int c; private static int f = 1; private event System.Action d; public S(int z) { this = default(S); a = z; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoStruct, "b", FeaturesResources.field, CSharpFeaturesResources.struct_), Diagnostic(RudeEditKind.InsertIntoStruct, "c", FeaturesResources.field, CSharpFeaturesResources.struct_), Diagnostic(RudeEditKind.InsertIntoStruct, "f = 1", FeaturesResources.field, CSharpFeaturesResources.struct_), Diagnostic(RudeEditKind.InsertIntoStruct, "d", CSharpFeaturesResources.event_field, CSharpFeaturesResources.struct_)); } [Fact] public void Field_Insert_IntoLayoutClass_Auto() { var src1 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Auto)] class C { private int a; } "; var src2 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Auto)] class C { private int a; private int b; private int c; private static int d; } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.b")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.c")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.d")), }); } [Fact] public void Field_Insert_IntoLayoutClass_Explicit() { var src1 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Explicit)] class C { [FieldOffset(0)] private int a; } "; var src2 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Explicit)] class C { [FieldOffset(0)] private int a; [FieldOffset(0)] private int b; [FieldOffset(4)] private int c; private static int d; } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "b", FeaturesResources.field, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "c", FeaturesResources.field, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "d", FeaturesResources.field, FeaturesResources.class_)); } [Fact] public void Field_Insert_IntoLayoutClass_Sequential() { var src1 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Sequential)] class C { private int a; } "; var src2 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Sequential)] class C { private int a; private int b; private int c; private static int d; } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "b", FeaturesResources.field, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "c", FeaturesResources.field, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "d", FeaturesResources.field, FeaturesResources.class_)); } [Fact] public void Field_Insert_WithInitializersAndLambdas1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); public C() { F(<N:0.1>c => c + 1</N:0.1>); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(b => b + 1); // new field public C() { F(<N:0.1>c => c + 1</N:0.1>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.B")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void Field_Insert_ConstructorReplacingImplicitConstructor_WithInitializersAndLambdas() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(b => b + 1); // new field public C() // new ctor replacing existing implicit constructor { F(c => c + 1); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.B")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact, WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")] public void Field_Insert_ParameterlessConstructorInsert_WithInitializersAndLambdas() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); public C(int x) {} } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); public C(int x) {} public C() // new ctor { F(c => c + 1); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, "public C()")); // TODO (bug https://github.com/dotnet/roslyn/issues/2504): //edits.VerifySemantics( // ActiveStatementsDescription.Empty, // new[] // { // SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<NamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) // }); } [Fact, WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")] public void Field_Insert_ConstructorInsert_WithInitializersAndLambdas1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(b => b + 1); // new field public C(int x) // new ctor { F(c => c + 1); } } "; var edits = GetTopEdits(src1, src2); _ = GetSyntaxMap(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, "public C(int x)")); // TODO (bug https://github.com/dotnet/roslyn/issues/2504): //edits.VerifySemantics( // ActiveStatementsDescription.Empty, // new[] // { // SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.B")), // SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<NamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) // }); } [Fact, WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")] public void Field_Insert_ConstructorInsert_WithInitializersButNoExistingLambdas1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(null); } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(null); int B = F(b => b + 1); // new field public C(int x) // new ctor { F(c => c + 1); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.B")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single()) }); } [Fact] public void Field_Insert_NotSupportedByRuntime() { var src1 = "class C { }"; var src2 = "class C { public int a = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities | EditAndContinueCapabilities.AddStaticFieldToExistingType, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "a = 1", FeaturesResources.field)); } [Fact] public void Field_Insert_Static_NotSupportedByRuntime() { var src1 = "class C { }"; var src2 = "class C { public static int a = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities | EditAndContinueCapabilities.AddInstanceFieldToExistingType, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "a = 1", FeaturesResources.field)); } [Fact] public void Field_Attribute_Add_NotSupportedByRuntime() { var src1 = @" class C { public int a = 1, x = 1; }"; var src2 = @" class C { [System.Obsolete]public int a = 1, x = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public int a = 1, x = 1;]@18 -> [[System.Obsolete]public int a = 1, x = 1;]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "public int a = 1, x = 1", FeaturesResources.field), Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "public int a = 1, x = 1", FeaturesResources.field)); } [Fact] public void Field_Attribute_Add() { var src1 = @" class C { public int a, b; }"; var src2 = @" class C { [System.Obsolete]public int a, b; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.a")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.b")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Field_Attribute_Add_WithInitializer() { var src1 = @" class C { int a; }"; var src2 = @" class C { [System.Obsolete]int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.a")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Field_Attribute_DeleteInsertUpdate_WithInitializer() { var srcA1 = "partial class C { int a = 1; }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { [System.Obsolete]int a = 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.a"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Field_Delete1() { var src1 = "class C { int a = 1; }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [int a = 1;]@10", "Delete [int a = 1]@10", "Delete [a = 1]@14"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.field, "a"))); } [Fact] public void Field_UnsafeModifier_Update() { var src1 = "struct Node { unsafe Node* left; }"; var src2 = "struct Node { Node* left; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [unsafe Node* left;]@14 -> [Node* left;]@14"); edits.VerifyRudeDiagnostics(); } [Fact] public void Field_ModifierAndType_Update() { var src1 = "struct Node { unsafe Node* left; }"; var src2 = "struct Node { Node left; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [unsafe Node* left;]@14 -> [Node left;]@14", "Update [Node* left]@21 -> [Node left]@14"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "Node left", FeaturesResources.field)); } [Theory] [InlineData("string", "string?")] [InlineData("object", "dynamic")] [InlineData("(int a, int b)", "(int a, int c)")] public void Field_Type_Update_RuntimeTypeUnchanged(string oldType, string newType) { var src1 = "class C { " + oldType + " F, G; }"; var src2 = "class C { " + newType + " F, G; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.G"))); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void Field_Type_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C { " + oldType + " F, G; }"; var src2 = "class C { " + newType + " F, G; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, newType + " F, G", FeaturesResources.field), Diagnostic(RudeEditKind.TypeUpdate, newType + " F, G", FeaturesResources.field)); } [Theory] [InlineData("string", "string?")] [InlineData("object", "dynamic")] [InlineData("(int a, int b)", "(int a, int c)")] public void Field_Event_Type_Update_RuntimeTypeUnchanged(string oldType, string newType) { var src1 = "class C { event System.Action<" + oldType + "> F, G; }"; var src2 = "class C { event System.Action<" + newType + "> F, G; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.G"))); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void Field_Event_Type_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C { event System.Action<" + oldType + "> F, G; }"; var src2 = "class C { event System.Action<" + newType + "> F, G; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "event System.Action<" + newType + "> F, G", FeaturesResources.event_), Diagnostic(RudeEditKind.TypeUpdate, "event System.Action<" + newType + "> F, G", FeaturesResources.event_)); } [Fact] public void Field_Type_Update_ReorderRemoveAdd() { var src1 = "class C { int F, G, H; bool U; }"; var src2 = "class C { string G, F; double V, U; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int F, G, H]@10 -> [string G, F]@10", "Reorder [G]@17 -> @17", "Update [bool U]@23 -> [double V, U]@23", "Insert [V]@30", "Delete [H]@20"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "G", FeaturesResources.field), Diagnostic(RudeEditKind.TypeUpdate, "string G, F", FeaturesResources.field), Diagnostic(RudeEditKind.TypeUpdate, "string G, F", FeaturesResources.field), Diagnostic(RudeEditKind.TypeUpdate, "double V, U", FeaturesResources.field), Diagnostic(RudeEditKind.Delete, "string G, F", DeletedSymbolDisplay(FeaturesResources.field, "H"))); } [Fact] public void Field_Event_Reorder() { var src1 = "class C { int a = 0; int b = 1; event int c = 2; }"; var src2 = "class C { event int c = 2; int a = 0; int b = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [event int c = 2;]@32 -> @10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "event int c = 2", CSharpFeaturesResources.event_field)); } [Fact] public void Field_Event_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { event int E = 2; }"; var srcA2 = "partial class C { event int E = 2; }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults(), }); } #endregion #region Properties [Theory] [InlineData("static")] [InlineData("virtual")] [InlineData("abstract")] [InlineData("override")] [InlineData("sealed override", "override")] public void Property_Modifiers_Update(string oldModifiers, string newModifiers = "") { if (oldModifiers != "") { oldModifiers += " "; } if (newModifiers != "") { newModifiers += " "; } var src1 = "class C { " + oldModifiers + "int F => 0; }"; var src2 = "class C { " + newModifiers + "int F => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [" + oldModifiers + "int F => 0;]@10 -> [" + newModifiers + "int F => 0;]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, newModifiers + "int F", FeaturesResources.property_)); } [Fact] public void Property_ExpressionBody_Rename() { var src1 = "class C { int P => 1; }"; var src2 = "class C { int Q => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "int Q", FeaturesResources.property_)); } [Fact] public void Property_ExpressionBody_Update() { var src1 = "class C { int P => 1; }"; var src2 = "class C { int P => 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [int P => 1;]@10 -> [int P => 2;]@10"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false) }); } [Fact, WorkItem(48628, "https://github.com/dotnet/roslyn/issues/48628")] public void Property_ExpressionBody_ModifierUpdate() { var src1 = "class C { int P => 1; }"; var src2 = "class C { unsafe int P => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [int P => 1;]@10 -> [unsafe int P => 1;]@10"); edits.VerifyRudeDiagnostics(); } [Fact] public void Property_ExpressionBodyToBlockBody1() { var src1 = "class C { int P => 1; }"; var src2 = "class C { int P { get { return 2; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P => 1;]@10 -> [int P { get { return 2; } }]@10", "Insert [{ get { return 2; } }]@16", "Insert [get { return 2; }]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false) }); } [Fact] public void Property_ExpressionBodyToBlockBody2() { var src1 = "class C { int P => 1; }"; var src2 = "class C { int P { get { return 2; } set { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P => 1;]@10 -> [int P { get { return 2; } set { } }]@10", "Insert [{ get { return 2; } set { } }]@16", "Insert [get { return 2; }]@18", "Insert [set { }]@36"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.set_P"), preserveLocalVariables: false) }); } [Fact] public void Property_BlockBodyToExpressionBody1() { var src1 = "class C { int P { get { return 2; } } }"; var src2 = "class C { int P => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P { get { return 2; } }]@10 -> [int P => 1;]@10", "Delete [{ get { return 2; } }]@16", "Delete [get { return 2; }]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false) }); } [Fact] public void Property_BlockBodyToExpressionBody2() { var src1 = "class C { int P { get { return 2; } set { } } }"; var src2 = "class C { int P => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P { get { return 2; } set { } }]@10 -> [int P => 1;]@10", "Delete [{ get { return 2; } set { } }]@16", "Delete [get { return 2; }]@18", "Delete [set { }]@36"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_setter, "P.set"))); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_ExpressionBodyToGetterExpressionBody() { var src1 = "class C { int P => 1; }"; var src2 = "class C { int P { get => 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P => 1;]@10 -> [int P { get => 2; }]@10", "Insert [{ get => 2; }]@16", "Insert [get => 2;]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_GetterExpressionBodyToExpressionBody() { var src1 = "class C { int P { get => 2; } }"; var src2 = "class C { int P => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P { get => 2; }]@10 -> [int P => 1;]@10", "Delete [{ get => 2; }]@16", "Delete [get => 2;]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_GetterBlockBodyToGetterExpressionBody() { var src1 = "class C { int P { get { return 2; } } }"; var src2 = "class C { int P { get => 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get { return 2; }]@18 -> [get => 2;]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_SetterBlockBodyToSetterExpressionBody() { var src1 = "class C { int P { set { } } }"; var src2 = "class C { int P { set => F(); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [set { }]@18 -> [set => F();]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_InitBlockBodyToInitExpressionBody() { var src1 = "class C { int P { init { } } }"; var src2 = "class C { int P { init => F(); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [init { }]@18 -> [init => F();]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod, preserveLocalVariables: false), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_GetterExpressionBodyToGetterBlockBody() { var src1 = "class C { int P { get => 2; } }"; var src2 = "class C { int P { get { return 2; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get => 2;]@18 -> [get { return 2; }]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_GetterBlockBodyWithSetterToGetterExpressionBodyWithSetter() { var src1 = "class C { int P { get => 2; set { Console.WriteLine(0); } } }"; var src2 = "class C { int P { get { return 2; } set { Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get => 2;]@18 -> [get { return 2; }]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_GetterExpressionBodyWithSetterToGetterBlockBodyWithSetter() { var src1 = "class C { int P { get { return 2; } set { Console.WriteLine(0); } } }"; var src2 = "class C { int P { get => 2; set { Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get { return 2; }]@18 -> [get => 2;]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_P"), preserveLocalVariables: false) }); } [Fact] public void Property_Rename1() { var src1 = "class C { int P { get { return 1; } } }"; var src2 = "class C { int Q { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "int Q", FeaturesResources.property_)); } [Fact] public void Property_Rename2() { var src1 = "class C { int I.P { get { return 1; } } }"; var src2 = "class C { int J.P { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "int J.P", FeaturesResources.property_)); } [Fact] public void Property_RenameAndUpdate() { var src1 = "class C { int P { get { return 1; } } }"; var src2 = "class C { int Q { get { return 2; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "int Q", FeaturesResources.property_)); } [Fact] public void PropertyDelete() { var src1 = "class C { int P { get { return 1; } } }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.property_, "P"))); } [Fact] public void PropertyReorder1() { var src1 = "class C { int P { get { return 1; } } int Q { get { return 1; } } }"; var src2 = "class C { int Q { get { return 1; } } int P { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [int Q { get { return 1; } }]@38 -> @10"); // TODO: we can allow the move since the property doesn't have a backing field edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "int Q", FeaturesResources.property_)); } [Fact] public void PropertyReorder2() { var src1 = "class C { int P { get; set; } int Q { get; set; } }"; var src2 = "class C { int Q { get; set; } int P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [int Q { get; set; }]@30 -> @10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "int Q", FeaturesResources.auto_property)); } [Fact] public void PropertyAccessorReorder_GetSet() { var src1 = "class C { int P { get { return 1; } set { } } }"; var src2 = "class C { int P { set { } get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [set { }]@36 -> @18"); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyAccessorReorder_GetInit() { var src1 = "class C { int P { get { return 1; } init { } } }"; var src2 = "class C { int P { init { } get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [init { }]@36 -> @18"); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyTypeUpdate() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { char P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P { get; set; }]@10 -> [char P { get; set; }]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "char P", FeaturesResources.property_)); } [Fact] public void PropertyUpdate_AddAttribute() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { [System.Obsolete]int P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int P", FeaturesResources.property_)); } [Fact] public void PropertyUpdate_AddAttribute_SupportedByRuntime() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { [System.Obsolete]int P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.P")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void PropertyAccessorUpdate_AddAttribute() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { int P { [System.Obsolete]get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "get", CSharpFeaturesResources.property_getter)); } [Fact] public void PropertyAccessorUpdate_AddAttribute2() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { int P { get; [System.Obsolete]set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "set", CSharpFeaturesResources.property_setter)); } [Fact] public void PropertyAccessorUpdate_AddAttribute_SupportedByRuntime() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { int P { [System.Obsolete]get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void PropertyAccessorUpdate_AddAttribute_SupportedByRuntime2() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { int P { get; [System.Obsolete]set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void PropertyInsert() { var src1 = "class C { }"; var src2 = "class C { int P { get => 1; set { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").GetMember("P"))); } [Fact] public void PropertyInsert_NotSupportedByRuntime() { var src1 = "class C { }"; var src2 = "class C { int P { get => 1; set { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "int P", FeaturesResources.auto_property)); } [WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] [Fact] public void PropertyInsert_PInvoke() { var src1 = @" using System; using System.Runtime.InteropServices; class C { }"; var src2 = @" using System; using System.Runtime.InteropServices; class C { private static extern int P1 { [DllImport(""x.dll"")]get; } private static extern int P2 { [DllImport(""x.dll"")]set; } private static extern int P3 { [DllImport(""x.dll"")]get; [DllImport(""x.dll"")]set; } } "; var edits = GetTopEdits(src1, src2); // CLR doesn't support methods without a body edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertExtern, "private static extern int P1", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertExtern, "private static extern int P2", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertExtern, "private static extern int P3", FeaturesResources.property_)); } [Fact] public void PropertyInsert_IntoStruct() { var src1 = @" struct S { public int a; public S(int z) { a = z; } } "; var src2 = @" struct S { public int a; private static int c { get; set; } private static int e { get { return 0; } set { } } private static int g { get; } = 1; private static int i { get; set; } = 1; private static int k => 1; public S(int z) { a = z; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoStruct, "private static int c { get; set; }", FeaturesResources.auto_property, CSharpFeaturesResources.struct_), Diagnostic(RudeEditKind.InsertIntoStruct, "private static int g { get; } = 1;", FeaturesResources.auto_property, CSharpFeaturesResources.struct_), Diagnostic(RudeEditKind.InsertIntoStruct, "private static int i { get; set; } = 1;", FeaturesResources.auto_property, CSharpFeaturesResources.struct_)); } [Fact] public void PropertyInsert_IntoLayoutClass_Sequential() { var src1 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Sequential)] class C { private int a; } "; var src2 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Sequential)] class C { private int a; private int b { get; set; } private static int c { get; set; } private int d { get { return 0; } set { } } private static int e { get { return 0; } set { } } private int f { get; } = 1; private static int g { get; } = 1; private int h { get; set; } = 1; private static int i { get; set; } = 1; private int j => 1; private static int k => 1; } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private int b { get; set; }", FeaturesResources.auto_property, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private static int c { get; set; }", FeaturesResources.auto_property, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private int f { get; } = 1;", FeaturesResources.auto_property, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private static int g { get; } = 1;", FeaturesResources.auto_property, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private int h { get; set; } = 1;", FeaturesResources.auto_property, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private static int i { get; set; } = 1;", FeaturesResources.auto_property, FeaturesResources.class_)); } // Design: Adding private accessors should also be allowed since we now allow adding private methods // and adding public properties and/or public accessors are not allowed. [Fact] public void PrivateProperty_AccessorAdd() { var src1 = "class C { int _p; int P { get { return 1; } } }"; var src2 = "class C { int _p; int P { get { return 1; } set { _p = value; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [set { _p = value; }]@44"); edits.VerifyRudeDiagnostics(); } [WorkItem(755975, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755975")] [Fact] public void PrivatePropertyAccessorDelete() { var src1 = "class C { int _p; int P { get { return 1; } set { _p = value; } } }"; var src2 = "class C { int _p; int P { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [set { _p = value; }]@44"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_setter, "P.set"))); } [Fact] public void PrivateAutoPropertyAccessorAdd1() { var src1 = "class C { int P { get; } }"; var src2 = "class C { int P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [set;]@23"); edits.VerifyRudeDiagnostics(); } [Fact] public void PrivateAutoPropertyAccessorAdd2() { var src1 = "class C { public int P { get; } }"; var src2 = "class C { public int P { get; private set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [private set;]@30"); edits.VerifyRudeDiagnostics(); } [Fact] public void PrivateAutoPropertyAccessorAdd4() { var src1 = "class C { public int P { get; } }"; var src2 = "class C { public int P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [set;]@30"); edits.VerifyRudeDiagnostics(); } [Fact] public void PrivateAutoPropertyAccessorAdd5() { var src1 = "class C { public int P { get; } }"; var src2 = "class C { public int P { get; internal set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [internal set;]@30"); edits.VerifyRudeDiagnostics(); } [Fact] public void PrivateAutoPropertyAccessorAdd6() { var src1 = "class C { int P { get; } = 1; }"; var src2 = "class C { int P { get; set; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [set;]@23"); edits.VerifyRudeDiagnostics(); } [Fact] public void PrivateAutoPropertyAccessorAdd_Init() { var src1 = "class C { int P { get; } = 1; }"; var src2 = "class C { int P { get; init; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [init;]@23"); edits.VerifyRudeDiagnostics(); } [WorkItem(755975, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755975")] [Fact] public void PrivateAutoPropertyAccessorDelete_Get() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { int P { set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [get;]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_getter, "P.get"))); } [Fact] public void AutoPropertyAccessor_SetToInit() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { int P { get; init; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [set;]@23 -> [init;]@23"); // not allowed since it changes the backing field readonly-ness and the signature of the setter (modreq) edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.AccessorKindUpdate, "init", CSharpFeaturesResources.property_setter)); } [Fact] public void AutoPropertyAccessor_InitToSet() { var src1 = "class C { int P { get; init; } }"; var src2 = "class C { int P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [init;]@23 -> [set;]@23"); // not allowed since it changes the backing field readonly-ness and the signature of the setter (modreq) edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.AccessorKindUpdate, "set", CSharpFeaturesResources.property_setter)); } [Fact] public void PrivateAutoPropertyAccessorDelete_Set() { var src1 = "class C { int P { get; set; } = 1; }"; var src2 = "class C { int P { get; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [set;]@23"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_setter, "P.set"))); } [Fact] public void PrivateAutoPropertyAccessorDelete_Init() { var src1 = "class C { int P { get; init; } = 1; }"; var src2 = "class C { int P { get; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [init;]@23"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_setter, "P.init"))); } [Fact] public void AutoPropertyAccessorUpdate() { var src1 = "class C { int P { get; } }"; var src2 = "class C { int P { set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get;]@18 -> [set;]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.AccessorKindUpdate, "set", CSharpFeaturesResources.property_setter)); } [WorkItem(992578, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/992578")] [Fact] public void InsertIncompleteProperty() { var src1 = "class C { }"; var src2 = "class C { public int P { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [public int P { }]@10", "Insert [{ }]@23"); edits.VerifyRudeDiagnostics(); } [Fact] public void Property_ReadOnlyRef_Insert() { var src1 = "class Test { }"; var src2 = "class Test { ref readonly int P { get; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [ref readonly int P { get; }]@13", "Insert [{ get; }]@32", "Insert [get;]@34"); edits.VerifyRudeDiagnostics(); } [Fact] public void Property_ReadOnlyRef_Update() { var src1 = "class Test { int P { get; } }"; var src2 = "class Test { ref readonly int P { get; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P { get; }]@13 -> [ref readonly int P { get; }]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "ref readonly int P", FeaturesResources.property_)); } [Fact] public void Property_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int P { get => 1; set { } } }"; var srcA2 = "partial class C { int P { get => 1; set { } } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod) }), DocumentResults(), }); } [Fact] public void PropertyInit_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int Q { get => 1; init { } }}"; var srcA2 = "partial class C { int Q { get => 1; init { } }}"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("Q").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("Q").SetMethod) }), DocumentResults(), }); } [Fact] public void AutoProperty_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int P { get; set; } int Q { get; init; } }"; var srcA2 = "partial class C { int P { get; set; } int Q { get; init; } }"; var srcB2 = "partial class C { }"; // Accessors need to be updated even though they do not have an explicit body. // There is still a sequence point generated for them whose location needs to be updated. EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("Q").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("Q").SetMethod), }), DocumentResults(), }); } [Fact] public void AutoPropertyWithInitializer_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int P { get; set; } = 1; }"; var srcA2 = "partial class C { int P { get; set; } = 1; }"; var srcB2 = "partial class C { }"; // Accessors need to be updated even though they do not have an explicit body. // There is still a sequence point generated for them whose location needs to be updated. EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults(), }); } [Fact] public void PropertyWithExpressionBody_Partial_InsertDeleteUpdate() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int P => 1; }"; var srcA2 = "partial class C { int P => 2; }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod) }), DocumentResults(), }); } [Fact] public void AutoProperty_ReadOnly_Add() { var src1 = @" struct S { int P { get; } }"; var src2 = @" struct S { readonly int P { get; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Property_InMutableStruct_ReadOnly_Add() { var src1 = @" struct S { int P1 { get => 1; } int P2 { get => 1; set {}} int P3 { get => 1; set {}} int P4 { get => 1; set {}} }"; var src2 = @" struct S { readonly int P1 { get => 1; } int P2 { readonly get => 1; set {}} int P3 { get => 1; readonly set {}} readonly int P4 { get => 1; set {}} }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int P1", CSharpFeaturesResources.property_getter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int P4", CSharpFeaturesResources.property_getter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int P4", CSharpFeaturesResources.property_setter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly get", CSharpFeaturesResources.property_getter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly set", CSharpFeaturesResources.property_setter)); } [Fact] public void Property_InReadOnlyStruct_ReadOnly_Add() { // indent to align accessor bodies and avoid updates caused by sequence point location changes var src1 = @" readonly struct S { int P1 { get => 1; } int P2 { get => 1; set {}} int P3 { get => 1; set {}} int P4 { get => 1; set {}} }"; var src2 = @" readonly struct S { readonly int P1 { get => 1; } int P2 { readonly get => 1; set {}} int P3 { get => 1; readonly set {}} readonly int P4 { get => 1; set {}} }"; var edits = GetTopEdits(src1, src2); // updates only for accessors whose modifiers were explicitly updated edits.VerifySemantics(new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember<IPropertySymbol>("P2").GetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember<IPropertySymbol>("P3").SetMethod, preserveLocalVariables: false) }); } #endregion #region Indexers [Theory] [InlineData("virtual")] [InlineData("abstract")] [InlineData("override")] [InlineData("sealed override", "override")] public void Indexer_Modifiers_Update(string oldModifiers, string newModifiers = "") { if (oldModifiers != "") { oldModifiers += " "; } if (newModifiers != "") { newModifiers += " "; } var src1 = "class C { " + oldModifiers + "int this[int a] => 0; }"; var src2 = "class C { " + newModifiers + "int this[int a] => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [" + oldModifiers + "int this[int a] => 0;]@10 -> [" + newModifiers + "int this[int a] => 0;]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, newModifiers + "int this[int a]", FeaturesResources.indexer_)); } [Fact] public void Indexer_GetterUpdate() { var src1 = "class C { int this[int a] { get { return 1; } } }"; var src2 = "class C { int this[int a] { get { return 2; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [get { return 1; }]@28 -> [get { return 2; }]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact] public void Indexer_SetterUpdate() { var src1 = "class C { int this[int a] { get { return 1; } set { System.Console.WriteLine(value); } } }"; var src2 = "class C { int this[int a] { get { return 1; } set { System.Console.WriteLine(value + 1); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [set { System.Console.WriteLine(value); }]@46 -> [set { System.Console.WriteLine(value + 1); }]@46"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item"), preserveLocalVariables: false) }); } [Fact] public void Indexer_InitUpdate() { var src1 = "class C { int this[int a] { get { return 1; } init { System.Console.WriteLine(value); } } }"; var src2 = "class C { int this[int a] { get { return 1; } init { System.Console.WriteLine(value + 1); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [init { System.Console.WriteLine(value); }]@46 -> [init { System.Console.WriteLine(value + 1); }]@46"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item"), preserveLocalVariables: false) }); } [Fact] public void IndexerWithExpressionBody_Update() { var src1 = "class C { int this[int a] => 1; }"; var src2 = "class C { int this[int a] => 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => 1;]@10 -> [int this[int a] => 2;]@10"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")] public void IndexerWithExpressionBody_Update_LiftedParameter() { var src1 = @" using System; class C { int this[int a] => new Func<int>(() => a + 1)() + 10; } "; var src2 = @" using System; class C { int this[int a] => new Func<int>(() => 2)() + 11; // not capturing a anymore }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => new Func<int>(() => a + 1)() + 10;]@35 -> [int this[int a] => new Func<int>(() => 2)() + 11;]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a")); } [Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")] public void IndexerWithExpressionBody_Update_LiftedParameter_2() { var src1 = @" using System; class C { int this[int a] => new Func<int>(() => a + 1)(); } "; var src2 = @" using System; class C { int this[int a] => new Func<int>(() => 2)(); // not capturing a anymore }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => new Func<int>(() => a + 1)();]@35 -> [int this[int a] => new Func<int>(() => 2)();]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a")); } [Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")] public void IndexerWithExpressionBody_Update_LiftedParameter_3() { var src1 = @" using System; class C { int this[int a] => new Func<int>(() => { return a + 1; })(); } "; var src2 = @" using System; class C { int this[int a] => new Func<int>(() => { return 2; })(); // not capturing a anymore }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => new Func<int>(() => { return a + 1; })();]@35 -> [int this[int a] => new Func<int>(() => { return 2; })();]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a")); } [Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")] public void IndexerWithExpressionBody_Update_LiftedParameter_4() { var src1 = @" using System; class C { int this[int a] => new Func<int>(delegate { return a + 1; })(); } "; var src2 = @" using System; class C { int this[int a] => new Func<int>(delegate { return 2; })(); // not capturing a anymore }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => new Func<int>(delegate { return a + 1; })();]@35 -> [int this[int a] => new Func<int>(delegate { return 2; })();]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a")); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_ExpressionBodyToBlockBody() { var src1 = "class C { int this[int a] => 1; }"; var src2 = "class C { int this[int a] { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => 1;]@10 -> [int this[int a] { get { return 1; } }]@10", "Insert [{ get { return 1; } }]@26", "Insert [get { return 1; }]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_BlockBodyToExpressionBody() { var src1 = "class C { int this[int a] { get { return 1; } } }"; var src2 = "class C { int this[int a] => 1; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] { get { return 1; } }]@10 -> [int this[int a] => 1;]@10", "Delete [{ get { return 1; } }]@26", "Delete [get { return 1; }]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_GetterExpressionBodyToBlockBody() { var src1 = "class C { int this[int a] { get => 1; } }"; var src2 = "class C { int this[int a] { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get => 1;]@28 -> [get { return 1; }]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_BlockBodyToGetterExpressionBody() { var src1 = "class C { int this[int a] { get { return 1; } } }"; var src2 = "class C { int this[int a] { get => 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get { return 1; }]@28 -> [get => 1;]@28"); edits.VerifyRudeDiagnostics(); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_GetterExpressionBodyToExpressionBody() { var src1 = "class C { int this[int a] { get => 1; } }"; var src2 = "class C { int this[int a] => 1; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] { get => 1; }]@10 -> [int this[int a] => 1;]@10", "Delete [{ get => 1; }]@26", "Delete [get => 1;]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_ExpressionBodyToGetterExpressionBody() { var src1 = "class C { int this[int a] => 1; }"; var src2 = "class C { int this[int a] { get => 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => 1;]@10 -> [int this[int a] { get => 1; }]@10", "Insert [{ get => 1; }]@26", "Insert [get => 1;]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_GetterBlockBodyToGetterExpressionBody() { var src1 = "class C { int this[int a] { get { return 1; } set { Console.WriteLine(0); } } }"; var src2 = "class C { int this[int a] { get => 1; set { Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get { return 1; }]@28 -> [get => 1;]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_SetterBlockBodyToSetterExpressionBody() { var src1 = "class C { int this[int a] { set { } } void F() { } }"; var src2 = "class C { int this[int a] { set => F(); } void F() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [set { }]@28 -> [set => F();]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_InitBlockBodyToInitExpressionBody() { var src1 = "class C { int this[int a] { init { } } void F() { } }"; var src2 = "class C { int this[int a] { init => F(); } void F() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [init { }]@28 -> [init => F();]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_GetterExpressionBodyToGetterBlockBody() { var src1 = "class C { int this[int a] { get => 1; set { Console.WriteLine(0); } } }"; var src2 = "class C { int this[int a] { get { return 1; } set { Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get => 1;]@28 -> [get { return 1; }]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_GetterAndSetterBlockBodiesToExpressionBody() { var src1 = "class C { int this[int a] { get { return 1; } set { Console.WriteLine(0); } } }"; var src2 = "class C { int this[int a] => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] { get { return 1; } set { Console.WriteLine(0); } }]@10 -> [int this[int a] => 1;]@10", "Delete [{ get { return 1; } set { Console.WriteLine(0); } }]@26", "Delete [get { return 1; }]@28", "Delete [set { Console.WriteLine(0); }]@46"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "int this[int a]", DeletedSymbolDisplay(CSharpFeaturesResources.indexer_setter, "this[int a].set"))); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_ExpressionBodyToGetterAndSetterBlockBodies() { var src1 = "class C { int this[int a] => 1; }"; var src2 = "class C { int this[int a] { get { return 1; } set { Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => 1;]@10 -> [int this[int a] { get { return 1; } set { Console.WriteLine(0); } }]@10", "Insert [{ get { return 1; } set { Console.WriteLine(0); } }]@26", "Insert [get { return 1; }]@28", "Insert [set { Console.WriteLine(0); }]@46"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.set_Item"), preserveLocalVariables: false) }); } [Fact] public void Indexer_Rename() { var src1 = "class C { int I.this[int a] { get { return 1; } } }"; var src2 = "class C { int J.this[int a] { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "int J.this[int a]", CSharpFeaturesResources.indexer)); } [Fact] public void Indexer_Reorder1() { var src1 = "class C { int this[int a] { get { return 1; } } int this[string a] { get { return 1; } } }"; var src2 = "class C { int this[string a] { get { return 1; } } int this[int a] { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [int this[string a] { get { return 1; } }]@48 -> @10"); edits.VerifyRudeDiagnostics(); } [Fact] public void Indexer_AccessorReorder() { var src1 = "class C { int this[int a] { get { return 1; } set { } } }"; var src2 = "class C { int this[int a] { set { } get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [set { }]@46 -> @28"); edits.VerifyRudeDiagnostics(); } [Fact] public void Indexer_TypeUpdate() { var src1 = "class C { int this[int a] { get; set; } }"; var src2 = "class C { string this[int a] { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] { get; set; }]@10 -> [string this[int a] { get; set; }]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "string this[int a]", CSharpFeaturesResources.indexer)); } [Fact] public void Tuple_TypeUpdate() { var src1 = "class C { (int, int) M() { throw new System.Exception(); } }"; var src2 = "class C { (string, int) M() { throw new System.Exception(); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int, int) M() { throw new System.Exception(); }]@10 -> [(string, int) M() { throw new System.Exception(); }]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "(string, int) M()", FeaturesResources.method)); } [Fact] public void TupleElementDelete() { var src1 = "class C { (int, int, int a) M() { return (1, 2, 3); } }"; var src2 = "class C { (int, int) M() { return (1, 2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int, int, int a) M() { return (1, 2, 3); }]@10 -> [(int, int) M() { return (1, 2); }]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "(int, int) M()", FeaturesResources.method)); } [Fact] public void TupleElementAdd() { var src1 = "class C { (int, int) M() { return (1, 2); } }"; var src2 = "class C { (int, int, int a) M() { return (1, 2, 3); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int, int) M() { return (1, 2); }]@10 -> [(int, int, int a) M() { return (1, 2, 3); }]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "(int, int, int a) M()", FeaturesResources.method)); } [Fact] public void Indexer_ParameterUpdate() { var src1 = "class C { int this[int a] { get; set; } }"; var src2 = "class C { int this[string a] { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "string a", FeaturesResources.parameter)); } [Fact] public void Indexer_AddGetAccessor() { var src1 = @" class Test { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); stringCollection[0] = ""hello""; } } class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { set { arr[i] = value; } } }"; var src2 = @" class Test { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); stringCollection[0] = ""hello""; } } class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { get { return arr[i]; } set { arr[i] = value; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [get { return arr[i]; }]@304"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InsertIntoGenericType, "get", CSharpFeaturesResources.indexer_getter)); } [Fact] public void Indexer_AddSetAccessor() { var src1 = @" class C { public int this[int i] { get { return default; } } }"; var src2 = @" class C { public int this[int i] { get { return default; } set { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [set { }]@67"); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").SetMethod)); } [Fact] public void Indexer_AddSetAccessor_GenericType() { var src1 = @" class C<T> { public T this[int i] { get { return default; } } }"; var src2 = @" class C<T> { public T this[int i] { get { return default; } set { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [set { }]@68"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoGenericType, "set", CSharpFeaturesResources.indexer_setter)); } [WorkItem(750109, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/750109")] [Fact] public void Indexer_DeleteGetAccessor() { var src1 = @" class C<T> { public T this[int i] { get { return arr[i]; } set { arr[i] = value; } } }"; var src2 = @" class C<T> { public T this[int i] { set { arr[i] = value; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [get { return arr[i]; }]@58"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "public T this[int i]", DeletedSymbolDisplay(CSharpFeaturesResources.indexer_getter, "this[int i].get"))); } [Fact] public void Indexer_DeleteSetAccessor() { var src1 = @" class C { public int this[int i] { get { return 0; } set { } } }"; var src2 = @" class C { public int this[int i] { get { return 0; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [set { }]@61"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "public int this[int i]", DeletedSymbolDisplay(CSharpFeaturesResources.indexer_setter, "this[int i].set"))); } [Fact, WorkItem(1174850, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1174850")] public void Indexer_Insert() { var src1 = "struct C { }"; var src2 = "struct C { public int this[int x, int y] { get { return x + y; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Indexer_ReadOnlyRef_Parameter_InsertWhole() { var src1 = "class Test { }"; var src2 = "class Test { int this[in int i] => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [int this[in int i] => throw null;]@13", "Insert [[in int i]]@21", "Insert [in int i]@22"); edits.VerifyRudeDiagnostics(); } [Fact] public void Indexer_ReadOnlyRef_Parameter_Update() { var src1 = "class Test { int this[int i] => throw null; }"; var src2 = "class Test { int this[in int i] => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int i]@22 -> [in int i]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "in int i", FeaturesResources.parameter)); } [Fact] public void Indexer_ReadOnlyRef_ReturnType_Insert() { var src1 = "class Test { }"; var src2 = "class Test { ref readonly int this[int i] => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [ref readonly int this[int i] => throw null;]@13", "Insert [[int i]]@34", "Insert [int i]@35"); edits.VerifyRudeDiagnostics(); } [Fact] public void Indexer_ReadOnlyRef_ReturnType_Update() { var src1 = "class Test { int this[int i] => throw null; }"; var src2 = "class Test { ref readonly int this[int i] => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int i] => throw null;]@13 -> [ref readonly int this[int i] => throw null;]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "ref readonly int this[int i]", FeaturesResources.indexer_)); } [Fact] public void Indexer_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int this[int x] { get => 1; set { } } }"; var srcA2 = "partial class C { int this[int x] { get => 1; set { } } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").SetMethod) }), DocumentResults(), }); } [Fact] public void IndexerInit_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int this[int x] { get => 1; init { } }}"; var srcA2 = "partial class C { int this[int x] { get => 1; init { } }}"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").SetMethod) }), DocumentResults(), }); } [Fact] public void AutoIndexer_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int this[int x] { get; set; } }"; var srcA2 = "partial class C { int this[int x] { get; set; } }"; var srcB2 = "partial class C { }"; // Accessors need to be updated even though they do not have an explicit body. // There is still a sequence point generated for them whose location needs to be updated. EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").SetMethod), }), DocumentResults(), }); } [Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")] public void IndexerWithExpressionBody_Partial_InsertDeleteUpdate_LiftedParameter() { var srcA1 = @" partial class C { }"; var srcB1 = @" partial class C { int this[int a] => new System.Func<int>(() => a + 1); }"; var srcA2 = @" partial class C { int this[int a] => new System.Func<int>(() => 2); // no capture }"; var srcB2 = @" partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a") }), DocumentResults(), }); } [Fact] public void AutoIndexer_ReadOnly_Add() { var src1 = @" struct S { int this[int x] { get; } }"; var src2 = @" struct S { readonly int this[int x] { get; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int this[int x]", CSharpFeaturesResources.indexer_getter)); } [Fact] public void Indexer_InMutableStruct_ReadOnly_Add() { var src1 = @" struct S { int this[int x] { get => 1; } int this[uint x] { get => 1; set {}} int this[byte x] { get => 1; set {}} int this[sbyte x] { get => 1; set {}} }"; var src2 = @" struct S { readonly int this[int x] { get => 1; } int this[uint x] { readonly get => 1; set {}} int this[byte x] { get => 1; readonly set {}} readonly int this[sbyte x] { get => 1; set {}} }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int this[int x]", CSharpFeaturesResources.indexer_getter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int this[sbyte x]", CSharpFeaturesResources.indexer_getter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int this[sbyte x]", CSharpFeaturesResources.indexer_setter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly get", CSharpFeaturesResources.indexer_getter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly set", CSharpFeaturesResources.indexer_setter)); } [Fact] public void Indexer_InReadOnlyStruct_ReadOnly_Add() { // indent to align accessor bodies and avoid updates caused by sequence point location changes var src1 = @" readonly struct S { int this[int x] { get => 1; } int this[uint x] { get => 1; set {}} int this[byte x] { get => 1; set {}} int this[sbyte x] { get => 1; set {}} }"; var src2 = @" readonly struct S { readonly int this[int x] { get => 1; } int this[uint x] { readonly get => 1; set {}} int this[byte x] { get => 1; readonly set {}} readonly int this[sbyte x] { get => 1; set {}} }"; var edits = GetTopEdits(src1, src2); // updates only for accessors whose modifiers were explicitly updated edits.VerifySemantics(new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.Parameters.Single().Type.Name == "UInt32").GetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.Parameters.Single().Type.Name == "Byte").SetMethod, preserveLocalVariables: false) }); } #endregion #region Events [Theory] [InlineData("static")] [InlineData("virtual")] [InlineData("abstract")] [InlineData("override")] [InlineData("sealed override", "override")] public void Event_Modifiers_Update(string oldModifiers, string newModifiers = "") { if (oldModifiers != "") { oldModifiers += " "; } if (newModifiers != "") { newModifiers += " "; } var src1 = "class C { " + oldModifiers + "event Action F { add {} remove {} } }"; var src2 = "class C { " + newModifiers + "event Action F { add {} remove {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [" + oldModifiers + "event Action F { add {} remove {} }]@10 -> [" + newModifiers + "event Action F { add {} remove {} }]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, newModifiers + "event Action F", FeaturesResources.event_)); } [Fact] public void EventAccessorReorder1() { var src1 = "class C { event int E { add { } remove { } } }"; var src2 = "class C { event int E { remove { } add { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [remove { }]@32 -> @24"); edits.VerifyRudeDiagnostics(); } [Fact] public void EventAccessorReorder2() { var src1 = "class C { event int E1 { add { } remove { } } event int E1 { add { } remove { } } }"; var src2 = "class C { event int E2 { remove { } add { } } event int E2 { remove { } add { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [event int E1 { add { } remove { } }]@10 -> [event int E2 { remove { } add { } }]@10", "Update [event int E1 { add { } remove { } }]@49 -> [event int E2 { remove { } add { } }]@49", "Reorder [remove { }]@33 -> @25", "Reorder [remove { }]@72 -> @64"); } [Fact] public void EventAccessorReorder3() { var src1 = "class C { event int E1 { add { } remove { } } event int E2 { add { } remove { } } }"; var src2 = "class C { event int E2 { remove { } add { } } event int E1 { remove { } add { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [event int E2 { add { } remove { } }]@49 -> @10", "Reorder [remove { }]@72 -> @25", "Reorder [remove { }]@33 -> @64"); } [Fact] public void EventInsert() { var src1 = "class C { }"; var src2 = "class C { event int E { remove { } add { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").GetMember("E"))); } [Fact] public void EventDelete() { var src1 = "class C { event int E { remove { } add { } } }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.event_, "E"))); } [Fact] public void EventInsert_IntoLayoutClass_Sequential() { var src1 = @" using System; using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Sequential)] class C { } "; var src2 = @" using System; using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Sequential)] class C { private event Action c { add { } remove { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Event_ExpressionBodyToBlockBody() { var src1 = @" using System; public class C { event Action E { add => F(); remove => F(); } } "; var src2 = @" using System; public class C { event Action E { add { F(); } remove { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [add => F();]@57 -> [add { F(); }]@56", "Update [remove => F();]@69 -> [remove { }]@69" ); edits.VerifySemanticDiagnostics(); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Event_BlockBodyToExpressionBody() { var src1 = @" using System; public class C { event Action E { add { F(); } remove { } } } "; var src2 = @" using System; public class C { event Action E { add => F(); remove => F(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [add { F(); }]@56 -> [add => F();]@57", "Update [remove { }]@69 -> [remove => F();]@69" ); edits.VerifySemanticDiagnostics(); } [Fact] public void Event_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { event int E { add { } remove { } } }"; var srcA2 = "partial class C { event int E { add { } remove { } } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E").AddMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E").RemoveMethod) }), DocumentResults(), }); } [Fact] public void Event_InMutableStruct_ReadOnly_Add() { var src1 = @" struct S { public event Action E { add {} remove {} } }"; var src2 = @" struct S { public readonly event Action E { add {} remove {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public readonly event Action E", FeaturesResources.event_)); } [Fact] public void Event_InReadOnlyStruct_ReadOnly_Add1() { var src1 = @" readonly struct S { public event Action E { add {} remove {} } }"; var src2 = @" readonly struct S { public readonly event Action E { add {} remove {} } }"; var edits = GetTopEdits(src1, src2); // Currently, an edit is produced eventhough bodies nor IsReadOnly attribute have changed. Consider improving. edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember<IEventSymbol>("E").AddMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember<IEventSymbol>("E").RemoveMethod)); } #endregion #region Parameter [Fact] public void ParameterRename_Method1() { var src1 = @"class C { public void M(int a) {} }"; var src2 = @"class C { public void M(int b) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@24 -> [int b]@24"); } [Fact] public void ParameterRename_Ctor1() { var src1 = @"class C { public C(int a) {} }"; var src2 = @"class C { public C(int b) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@19 -> [int b]@19"); } [Fact] public void ParameterRename_Operator1() { var src1 = @"class C { public static implicit operator int(C a) {} }"; var src2 = @"class C { public static implicit operator int(C b) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [C a]@46 -> [C b]@46"); } [Fact] public void ParameterRename_Operator2() { var src1 = @"class C { public static int operator +(C a, C b) { return 0; } }"; var src2 = @"class C { public static int operator +(C a, C x) { return 0; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [C b]@44 -> [C x]@44"); } [Fact] public void ParameterRename_Indexer2() { var src1 = @"class C { public int this[int a, int b] { get { return 0; } } }"; var src2 = @"class C { public int this[int a, int x] { get { return 0; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int b]@33 -> [int x]@33"); } [Fact] public void ParameterInsert1() { var src1 = @"class C { public void M() {} }"; var src2 = @"class C { public void M(int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [int a]@24"); } [Fact] public void ParameterInsert2() { var src1 = @"class C { public void M(int a) {} }"; var src2 = @"class C { public void M(int a, ref int b) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int a)]@23 -> [(int a, ref int b)]@23", "Insert [ref int b]@31"); } [Fact] public void ParameterDelete1() { var src1 = @"class C { public void M(int a) {} }"; var src2 = @"class C { public void M() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [int a]@24"); } [Fact] public void ParameterDelete2() { var src1 = @"class C { public void M(int a, int b) {} }"; var src2 = @"class C { public void M(int b) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int a, int b)]@23 -> [(int b)]@23", "Delete [int a]@24"); } [Fact] public void ParameterUpdate() { var src1 = @"class C { public void M(int a) {} }"; var src2 = @"class C { public void M(int b) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@24 -> [int b]@24"); } [Fact] public void ParameterReorder() { var src1 = @"class C { public void M(int a, int b) {} }"; var src2 = @"class C { public void M(int b, int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [int b]@31 -> @24"); } [Fact] public void ParameterReorderAndUpdate() { var src1 = @"class C { public void M(int a, int b) {} }"; var src2 = @"class C { public void M(int b, int c) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [int b]@31 -> @24", "Update [int a]@24 -> [int c]@31"); } [Theory] [InlineData("string", "string?")] [InlineData("object", "dynamic")] [InlineData("(int a, int b)", "(int a, int c)")] public void Parameter_Type_Update_RuntimeTypeUnchanged(string oldType, string newType) { var src1 = "class C { static void M(" + oldType + " a) {} }"; var src2 = "class C { static void M(" + newType + " a) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M"))); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void Parameter_Type_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C { static void M(" + oldType + " a) {} }"; var src2 = "class C { static void M(" + newType + " a) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, newType + " a", FeaturesResources.parameter)); } [Fact] public void Parameter_Type_Nullable() { var src1 = @" #nullable enable class C { static void M(string a) { } } "; var src2 = @" #nullable disable class C { static void M(string a) { } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Theory] [InlineData("this")] [InlineData("ref")] [InlineData("out")] [InlineData("params")] public void Parameter_Modifier_Remove(string modifier) { var src1 = @"static class C { static void F(" + modifier + " int[] a) { } }"; var src2 = @"static class C { static void F(int[] a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "int[] a", FeaturesResources.parameter)); } [Theory] [InlineData("int a = 1", "int a = 2")] [InlineData("int a = 1", "int a")] [InlineData("int a", "int a = 2")] [InlineData("object a = null", "object a")] [InlineData("object a", "object a = null")] [InlineData("double a = double.NaN", "double a = 1.2")] public void Parameter_Initializer_Update(string oldParameter, string newParameter) { var src1 = @"static class C { static void F(" + oldParameter + ") { } }"; var src2 = @"static class C { static void F(" + newParameter + ") { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, newParameter, FeaturesResources.parameter)); } [Fact] public void Parameter_Initializer_NaN() { var src1 = @"static class C { static void F(double a = System.Double.NaN) { } }"; var src2 = @"static class C { static void F(double a = double.NaN) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Parameter_Initializer_InsertDeleteUpdate() { var srcA1 = @"partial class C { }"; var srcB1 = @"partial class C { public static void F(int x = 1) {} }"; var srcA2 = @"partial class C { public static void F(int x = 2) {} }"; var srcB2 = @"partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.InitializerUpdate, "int x = 2", FeaturesResources.parameter) }), DocumentResults(), }); } [Fact] public void Parameter_Attribute_Insert() { var attribute = "public class A : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M(int a) {} }"; var src2 = attribute + @"class C { public void M([A]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@63 -> [[A]int a]@63"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Parameter_Attribute_Insert_SupportedByRuntime_NonCustomAttribute() { var src1 = @"class C { public void M(int a) {} }"; var src2 = @"class C { public void M([System.Runtime.InteropServices.InAttribute]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@24 -> [[System.Runtime.InteropServices.InAttribute]int a]@24"); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities, Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Insert_SupportedByRuntime_SecurityAttribute1() { var attribute = "public class AAttribute : System.Security.Permissions.SecurityAttribute { }\n\n"; var src1 = attribute + @"class C { public void M(int a) {} }"; var src2 = attribute + @"class C { public void M([A]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@101 -> [[A]int a]@101"); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities, Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Insert_SupportedByRuntime_SecurityAttribute2() { var attribute = "public class BAttribute : System.Security.Permissions.SecurityAttribute { }\n\n" + "public class AAttribute : BAttribute { }\n\n"; var src1 = attribute + @"class C { public void M(int a) {} }"; var src2 = attribute + @"class C { public void M([A]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@143 -> [[A]int a]@143"); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities, Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Insert_NotSupportedByRuntime1() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M(int a) {} }"; var src2 = attribute + @"class C { public void M([A]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@72 -> [[A]int a]@72"); edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Insert_NotSupportedByRuntime2() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M([A]int a) {} }"; var src2 = attribute + @"class C { public void M([A, B]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]int a]@120 -> [[A, B]int a]@120"); edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Delete_NotSupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M([A]int a) {} }"; var src2 = attribute + @"class C { public void M(int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]int a]@72 -> [int a]@72"); edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Update_NotSupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M([System.Obsolete(""1""), B]int a) {} }"; var src2 = attribute + @"class C { public void M([System.Obsolete(""2""), A]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete(\"1\"), B]int a]@120 -> [[System.Obsolete(\"2\"), A]int a]@120"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Update() { var attribute = "class A : System.Attribute { public A(int x) {} } "; var src1 = attribute + "class C { void F([A(0)]int a) {} }"; var src2 = attribute + "class C { void F([A(1)]int a) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A(0)]int a]@67 -> [[A(1)]int a]@67"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Parameter_Attribute_Update_WithBodyUpdate() { var attribute = "class A : System.Attribute { public A(int x) {} } "; var src1 = attribute + "class C { void F([A(0)]int a) { F(0); } }"; var src2 = attribute + "class C { void F([A(1)]int a) { F(1); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void F([A(0)]int a) { F(0); }]@60 -> [void F([A(1)]int a) { F(1); }]@60", "Update [[A(0)]int a]@67 -> [[A(1)]int a]@67"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } #endregion #region Method Type Parameter [Fact] public void MethodTypeParameterInsert1() { var src1 = @"class C { public void M() {} }"; var src2 = @"class C { public void M<A>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [<A>]@23", "Insert [A]@24"); } [Fact] public void MethodTypeParameterInsert2() { var src1 = @"class C { public void M<A>() {} }"; var src2 = @"class C { public void M<A,B>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [<A>]@23 -> [<A,B>]@23", "Insert [B]@26"); } [Fact] public void MethodTypeParameterDelete1() { var src1 = @"class C { public void M<A>() {} }"; var src2 = @"class C { public void M() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [<A>]@23", "Delete [A]@24"); } [Fact] public void MethodTypeParameterDelete2() { var src1 = @"class C { public void M<A,B>() {} }"; var src2 = @"class C { public void M<B>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [<A,B>]@23 -> [<B>]@23", "Delete [A]@24"); } [Fact] public void MethodTypeParameterUpdate() { var src1 = @"class C { public void M<A>() {} }"; var src2 = @"class C { public void M<B>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [A]@24 -> [B]@24"); } [Fact] public void MethodTypeParameterReorder() { var src1 = @"class C { public void M<A,B>() {} }"; var src2 = @"class C { public void M<B,A>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [B]@26 -> @24"); } [Fact] public void MethodTypeParameterReorderAndUpdate() { var src1 = @"class C { public void M<A,B>() {} }"; var src2 = @"class C { public void M<B,C>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [B]@26 -> @24", "Update [A]@24 -> [C]@26"); } [Fact] public void MethodTypeParameter_Attribute_Insert1() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M<T>() {} }"; var src2 = attribute + @"class C { public void M<[A]T>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [T]@72 -> [[A]T]@72"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericMethodUpdate, "T"), Diagnostic(RudeEditKind.GenericMethodTriviaUpdate, "", FeaturesResources.method)); } [Fact] public void MethodTypeParameter_Attribute_Insert2() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M<[A]T>() {} }"; var src2 = attribute + @"class C { public void M<[A, B]T>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]T]@120 -> [[A, B]T]@120"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericMethodUpdate, "T"), Diagnostic(RudeEditKind.GenericMethodTriviaUpdate, "", FeaturesResources.method)); } [Fact] public void MethodTypeParameter_Attribute_Delete() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M<[A]T>() {} }"; var src2 = attribute + @"class C { public void M<T>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]T]@72 -> [T]@72"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericMethodTriviaUpdate, "", FeaturesResources.method), Diagnostic(RudeEditKind.GenericMethodUpdate, "T")); } [Fact] public void MethodTypeParameter_Attribute_Update_NotSupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M<[System.Obsolete(""1""), B]T>() {} }"; var src2 = attribute + @"class C { public void M<[System.Obsolete(""2""), A]T>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete(\"1\"), B]T]@120 -> [[System.Obsolete(\"2\"), A]T]@120"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericMethodUpdate, "T")); } [Fact] public void MethodTypeParameter_Attribute_Update() { var attribute = "class A : System.Attribute { public A(int x) {} } "; var src1 = attribute + "class C { void F<[A(0)]T>(T a) {} }"; var src2 = attribute + "class C { void F<[A(1)]T>(T a) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A(0)]T]@67 -> [[A(1)]T]@67"); edits.VerifyRudeDiagnostics( EditAndContinueTestHelpers.Net6RuntimeCapabilities, Diagnostic(RudeEditKind.GenericMethodUpdate, "T")); } [Fact] public void MethodTypeParameter_Attribute_Update_WithBodyUpdate() { var attribute = "class A : System.Attribute { public A(int x) {} } "; var src1 = attribute + "class C { void F<[A(0)]T>(T a) { F(0); } }"; var src2 = attribute + "class C { void F<[A(1)]T>(T a) { F(1); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void F<[A(0)]T>(T a) { F(0); }]@60 -> [void F<[A(1)]T>(T a) { F(1); }]@60", "Update [[A(0)]T]@67 -> [[A(1)]T]@67"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.GenericMethodUpdate, "void F<[A(1)]T>(T a)"), Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericMethodUpdate, "T")); } #endregion #region Type Type Parameter [Fact] public void TypeTypeParameterInsert1() { var src1 = @"class C {}"; var src2 = @"class C<A> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [<A>]@7", "Insert [A]@8"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "A", FeaturesResources.type_parameter)); } [Fact] public void TypeTypeParameterInsert2() { var src1 = @"class C<A> {}"; var src2 = @"class C<A,B> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [<A>]@7 -> [<A,B>]@7", "Insert [B]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "B", FeaturesResources.type_parameter)); } [Fact] public void TypeTypeParameterDelete1() { var src1 = @"class C<A> { }"; var src2 = @"class C { } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [<A>]@7", "Delete [A]@8"); } [Fact] public void TypeTypeParameterDelete2() { var src1 = @"class C<A,B> {}"; var src2 = @"class C<B> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [<A,B>]@7 -> [<B>]@7", "Delete [A]@8"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "class C<B>", DeletedSymbolDisplay(FeaturesResources.type_parameter, "A"))); } [Fact] public void TypeTypeParameterUpdate() { var src1 = @"class C<A> {}"; var src2 = @"class C<B> {} "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [A]@8 -> [B]@8"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "B", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "B")); } [Fact] public void TypeTypeParameterReorder() { var src1 = @"class C<A,B> { }"; var src2 = @"class C<B,A> { } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [B]@10 -> @8"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "B", FeaturesResources.type_parameter)); } [Fact] public void TypeTypeParameterReorderAndUpdate() { var src1 = @"class C<A,B> {}"; var src2 = @"class C<B,C> {} "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [B]@10 -> @8", "Update [A]@8 -> [C]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "B", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.Renamed, "C", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "C")); } [Fact] public void TypeTypeParameterAttributeInsert1() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C<T> {}"; var src2 = attribute + @"class C<[A]T> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [T]@56 -> [[A]T]@56"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void TypeTypeParameterAttributeInsert2() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C<[A]T> {}"; var src2 = attribute + @"class C<[A, B]T> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]T]@104 -> [[A, B]T]@104"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void TypeTypeParameterAttributeInsert_SupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C<T> {}"; var src2 = attribute + @"class C<[A]T> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [T]@56 -> [[A]T]@56"); edits.VerifyRudeDiagnostics( EditAndContinueTestHelpers.Net6RuntimeCapabilities, Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void TypeTypeParameterAttributeDelete() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C<[A]T> {}"; var src2 = attribute + @"class C<T> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]T]@56 -> [T]@56"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void TypeTypeParameterAttributeUpdate() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C<[System.Obsolete(""1""), B]T> {}"; var src2 = attribute + @"class C<[System.Obsolete(""2""), A]T> {} "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete(\"1\"), B]T]@104 -> [[System.Obsolete(\"2\"), A]T]@104"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void TypeTypeParameter_Partial_Attribute_AddMultiple() { var attributes = @" class A : System.Attribute {} class B : System.Attribute {} "; var srcA1 = "partial class C<T> { }" + attributes; var srcB1 = "partial class C<T> { }"; var srcA2 = "partial class C<[A]T> { }" + attributes; var srcB2 = "partial class C<[B]T> { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "T"), }), DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "T"), }), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void TypeTypeParameter_Partial_Attribute_AddMultiple_Reloadable() { var attributes = @" class A : System.Attribute {} class B : System.Attribute {} "; var srcA1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C<T> { }" + attributes; var srcB1 = "partial class C<T> { }"; var srcA2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C<[A]T> { }" + attributes; var srcB2 = "partial class C<[B]T> { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C") }), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C") }), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } #endregion #region Type Parameter Constraints [Theory] [InlineData("nonnull")] [InlineData("struct")] [InlineData("class")] [InlineData("new()")] [InlineData("unmanaged")] [InlineData("System.IDisposable")] [InlineData("System.Delegate")] public void TypeConstraint_Insert(string newConstraint) { var src1 = "class C<S,T> { }"; var src2 = "class C<S,T> where T : " + newConstraint + " { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [where T : " + newConstraint + "]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingConstraints, "where T : " + newConstraint, FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "where T : " + newConstraint)); } [Theory] [InlineData("nonnull")] [InlineData("struct")] [InlineData("class")] [InlineData("new()")] [InlineData("unmanaged")] [InlineData("System.IDisposable")] [InlineData("System.Delegate")] public void TypeConstraint_Delete(string oldConstraint) { var src1 = "class C<S,T> where T : " + oldConstraint + " { }"; var src2 = "class C<S,T> { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [where T : " + oldConstraint + "]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingConstraints, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Theory] [InlineData("string", "string?")] [InlineData("(int a, int b)", "(int a, int c)")] public void TypeConstraint_Update_RuntimeTypeUnchanged(string oldType, string newType) { // note: dynamic is not allowed in constraints var src1 = "class C<T> where T : System.Collections.Generic.List<" + oldType + "> {}"; var src2 = "class C<T> where T : System.Collections.Generic.List<" + newType + "> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.GenericTypeUpdate, "where T : System.Collections.Generic.List<" + newType + ">")); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void TypeConstraint_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C<T> where T : System.Collections.Generic.List<" + oldType + "> {}"; var src2 = "class C<T> where T : System.Collections.Generic.List<" + newType + "> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingConstraints, "where T : System.Collections.Generic.List<" + newType + ">", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "where T : System.Collections.Generic.List<" + newType + ">")); } [Fact] public void TypeConstraint_Delete_WithParameter() { var src1 = "class C<S,T> where S : new() where T : class { }"; var src2 = "class C<S> where S : new() { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "class C<S>", DeletedSymbolDisplay(FeaturesResources.type_parameter, "T"))); } [Fact] public void TypeConstraint_MultipleClauses_Insert() { var src1 = "class C<S,T> where T : class { }"; var src2 = "class C<S,T> where S : unmanaged where T : class { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [where S : unmanaged]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingConstraints, "where S : unmanaged", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "where S : unmanaged")); } [Fact] public void TypeConstraint_MultipleClauses_Delete() { var src1 = "class C<S,T> where S : new() where T : class { }"; var src2 = "class C<S,T> where T : class { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [where S : new()]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingConstraints, "S", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "S")); } [Fact] public void TypeConstraint_MultipleClauses_Reorder() { var src1 = "class C<S,T> where S : struct where T : class { }"; var src2 = "class C<S,T> where T : class where S : struct { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [where T : class]@30 -> @13"); edits.VerifyRudeDiagnostics(); } [Fact] public void TypeConstraint_MultipleClauses_UpdateAndReorder() { var src1 = "class C<S,T> where S : new() where T : class { }"; var src2 = "class C<T,S> where T : class, I where S : class, new() { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [where T : class]@29 -> @13", "Reorder [T]@10 -> @8", "Update [where T : class]@29 -> [where T : class, I]@13", "Update [where S : new()]@13 -> [where S : class, new()]@32"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.ChangingConstraints, "where T : class, I", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "where T : class, I"), Diagnostic(RudeEditKind.ChangingConstraints, "where S : class, new()", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "where S : class, new()")); } #endregion #region Top Level Statements [Fact] public void TopLevelStatements_Update() { var src1 = @" using System; Console.WriteLine(""Hello""); "; var src2 = @" using System; Console.WriteLine(""Hello World""); "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [Console.WriteLine(\"Hello\");]@19 -> [Console.WriteLine(\"Hello World\");]@19"); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("<Program>$.<Main>$"))); } [Fact] public void TopLevelStatements_InsertAndUpdate() { var src1 = @" using System; Console.WriteLine(""Hello""); "; var src2 = @" using System; Console.WriteLine(""Hello World""); Console.WriteLine(""What is your name?""); var name = Console.ReadLine(); "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Console.WriteLine(\"Hello\");]@19 -> [Console.WriteLine(\"Hello World\");]@19", "Insert [Console.WriteLine(\"What is your name?\");]@54", "Insert [var name = Console.ReadLine();]@96"); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("<Program>$.<Main>$"))); } [Fact] public void TopLevelStatements_Insert_NoImplicitMain() { var src1 = @" using System; "; var src2 = @" using System; Console.WriteLine(""Hello World""); "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [Console.WriteLine(\"Hello World\");]@19"); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("<Program>$.<Main>$"))); } [Fact] public void TopLevelStatements_Insert_ImplicitMain() { var src1 = @" using System; Console.WriteLine(""Hello""); "; var src2 = @" using System; Console.WriteLine(""Hello""); Console.WriteLine(""World""); "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [Console.WriteLine(\"World\");]@48"); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("<Program>$.<Main>$"))); } [Fact] public void TopLevelStatements_Delete_NoImplicitMain() { var src1 = @" using System; Console.WriteLine(""Hello World""); "; var src2 = @" using System; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [Console.WriteLine(\"Hello World\");]@19"); edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.Delete, null, CSharpFeaturesResources.global_statement)); } [Fact] public void TopLevelStatements_Delete_ImplicitMain() { var src1 = @" using System; Console.WriteLine(""Hello""); Console.WriteLine(""World""); "; var src2 = @" using System; Console.WriteLine(""Hello""); "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [Console.WriteLine(\"World\");]@48"); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("<Program>$.<Main>$"))); } [Fact] public void TopLevelStatements_StackAlloc() { var src1 = @"unsafe { var x = stackalloc int[3]; System.Console.Write(1); }"; var src2 = @"unsafe { var x = stackalloc int[3]; System.Console.Write(2); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", CSharpFeaturesResources.global_statement)); } [Fact] public void TopLevelStatements_VoidToInt1() { var src1 = @" using System; Console.Write(1); "; var src2 = @" using System; Console.Write(1); return 1; "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return 1;")); } [Fact] public void TopLevelStatements_VoidToInt2() { var src1 = @" using System; Console.Write(1); return; "; var src2 = @" using System; Console.Write(1); return 1; "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return 1;")); } [Fact] public void TopLevelStatements_VoidToInt3() { var src1 = @" using System; Console.Write(1); int Goo() { return 1; } "; var src2 = @" using System; Console.Write(1); return 1; int Goo() { return 1; } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return 1;")); } [Fact] public void TopLevelStatements_AddAwait() { var src1 = @" using System.Threading.Tasks; await Task.Delay(100); "; var src2 = @" using System.Threading.Tasks; await Task.Delay(100); await Task.Delay(200); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "await", CSharpFeaturesResources.await_expression)); } [Fact] public void TopLevelStatements_DeleteAwait() { var src1 = @" using System.Threading.Tasks; await Task.Delay(100); await Task.Delay(200); "; var src2 = @" using System.Threading.Tasks; await Task.Delay(100); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, null, CSharpFeaturesResources.await_expression)); } [Fact] public void TopLevelStatements_VoidToTask() { var src1 = @" using System; using System.Threading.Tasks; Console.Write(1); "; var src2 = @" using System; using System.Threading.Tasks; await Task.Delay(100); Console.Write(1); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "await Task.Delay(100);")); } [Fact] public void TopLevelStatements_TaskToTaskInt() { var src1 = @" using System; using System.Threading.Tasks; await Task.Delay(100); Console.Write(1); "; var src2 = @" using System; using System.Threading.Tasks; await Task.Delay(100); Console.Write(1); return 1; "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return 1;")); } [Fact] public void TopLevelStatements_VoidToTaskInt() { var src1 = @" using System; using System.Threading.Tasks; Console.Write(1); "; var src2 = @" using System; using System.Threading.Tasks; Console.Write(1); return await GetInt(); Task<int> GetInt() { return Task.FromResult(1); } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return await GetInt();")); } [Fact] public void TopLevelStatements_IntToVoid1() { var src1 = @" using System; Console.Write(1); return 1; "; var src2 = @" using System; Console.Write(1); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "Console.Write(1);")); } [Fact] public void TopLevelStatements_IntToVoid2() { var src1 = @" using System; Console.Write(1); return 1; "; var src2 = @" using System; Console.Write(1); return; "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return;")); } [Fact] public void TopLevelStatements_IntToVoid3() { var src1 = @" using System; Console.Write(1); return 1; int Goo() { return 1; } "; var src2 = @" using System; Console.Write(1); int Goo() { return 1; } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "int Goo()\r\n{\r\n return 1;\r\n}")); } [Fact] public void TopLevelStatements_IntToVoid4() { var src1 = @" using System; Console.Write(1); return 1; public class C { public int Goo() { return 1; } } "; var src2 = @" using System; Console.Write(1); public class C { public int Goo() { return 1; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "Console.Write(1);")); } [Fact] public void TopLevelStatements_TaskToVoid() { var src1 = @" using System; using System.Threading.Tasks; await Task.Delay(100); Console.Write(1); "; var src2 = @" using System; using System.Threading.Tasks; Console.Write(1); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "Console.Write(1);"), Diagnostic(RudeEditKind.Delete, null, CSharpFeaturesResources.await_expression)); } [Fact] public void TopLevelStatements_TaskIntToTask() { var src1 = @" using System; using System.Threading.Tasks; await Task.Delay(100); Console.Write(1); return 1; "; var src2 = @" using System; using System.Threading.Tasks; await Task.Delay(100); Console.Write(1); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "Console.Write(1);")); } [Fact] public void TopLevelStatements_TaskIntToVoid() { var src1 = @" using System; using System.Threading.Tasks; Console.Write(1); return await GetInt(); Task<int> GetInt() { return Task.FromResult(1); } "; var src2 = @" using System; using System.Threading.Tasks; Console.Write(1); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "Console.Write(1);"), Diagnostic(RudeEditKind.Delete, null, CSharpFeaturesResources.await_expression)); } [Fact] public void TopLevelStatements_WithLambda_Insert() { var src1 = @" using System; Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; "; var src2 = @" using System; Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; Console.WriteLine(1); "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("<Program>$.<Main>$"), syntaxMap[0]) }); } [Fact] public void TopLevelStatements_WithLambda_Update() { var src1 = @" using System; Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; Console.WriteLine(1); public class C { } "; var src2 = @" using System; Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; Console.WriteLine(2); public class C { } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("<Program>$.<Main>$"), syntaxMap[0]) }); } [Fact] public void TopLevelStatements_WithLambda_Delete() { var src1 = @" using System; Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; Console.WriteLine(1); public class C { } "; var src2 = @" using System; Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; public class C { } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("<Program>$.<Main>$"), syntaxMap[0]) }); } [Fact] public void TopLevelStatements_UpdateMultiple() { var src1 = @" using System; Console.WriteLine(1); Console.WriteLine(2); public class C { } "; var src2 = @" using System; Console.WriteLine(3); Console.WriteLine(4); public class C { } "; var edits = GetTopEdits(src1, src2); // Since each individual statement is a separate update to a separate node, this just validates we correctly // only analyze the things once edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("<Program>$.<Main>$"))); } [Fact] public void TopLevelStatements_MoveToOtherFile() { var srcA1 = @" using System; Console.WriteLine(1); public class A { }"; var srcB1 = @" using System; public class B { }"; var srcA2 = @" using System; public class A { }"; var srcB2 = @" using System; Console.WriteLine(2); public class B { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new [] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("<Program>$.<Main>$")) }), }); } #endregion } }
-1
dotnet/roslyn
55,409
Use FixedSize API
tmat
2021-08-04T19:30:40Z
2021-08-04T21:53:46Z
e0112742bff208dd0546de45e36f7b52058a45a3
c90bf0ec986010051662c8e1fbc872c2fd86bc4e
Use FixedSize API.
./src/EditorFeatures/Core/Implementation/NavigationBar/NavigationBarController.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Implementation.Classification; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Tagging; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Tagging; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; using IUIThreadOperationExecutor = Microsoft.VisualStudio.Utilities.IUIThreadOperationExecutor; namespace Microsoft.CodeAnalysis.Editor.Implementation.NavigationBar { /// <summary> /// The controller for navigation bars. /// </summary> /// <remarks> /// The threading model for this class is simple: all non-static members are affinitized to the /// UI thread. /// </remarks> internal partial class NavigationBarController : ForegroundThreadAffinitizedObject, IDisposable { private readonly INavigationBarPresenter _presenter; private readonly ITextBuffer _subjectBuffer; private readonly IUIThreadOperationExecutor _uiThreadOperationExecutor; private readonly IAsynchronousOperationListener _asyncListener; private bool _disconnected = false; /// <summary> /// Latest model and selected items produced once <see cref="SelectItemAsync"/> completes and presents the /// single item to the view. These can then be read in when the dropdown is expanded and we want to show all /// items. /// </summary> private (NavigationBarModel model, NavigationBarSelectedTypeAndMember selectedInfo) _latestModelAndSelectedInfo_OnlyAccessOnUIThread; /// <summary> /// The last full information we have presented. If we end up wanting to present the same thing again, we can /// just skip doing that as the UI will already know about this. /// </summary> private (ImmutableArray<NavigationBarProjectItem> projectItems, NavigationBarProjectItem? selectedProjectItem, NavigationBarModel model, NavigationBarSelectedTypeAndMember selectedInfo) _lastPresentedInfo; /// <summary> /// Source of events that should cause us to update the nav bar model with new information. /// </summary> private readonly ITaggerEventSource _eventSource; private readonly CancellationTokenSource _cancellationTokenSource = new(); /// <summary> /// Queue to batch up work to do to compute the current model. Used so we can batch up a lot of events and only /// compute the model once for every batch. The <c>bool</c> type parameter isn't used, but is provided as this /// type is generic. /// </summary> private readonly AsyncBatchingWorkQueue<bool, NavigationBarModel> _computeModelQueue; /// <summary> /// Queue to batch up work to do to determine the selected item. Used so we can batch up a lot of events and /// only compute the selected item once for every batch. /// </summary> private readonly AsyncBatchingWorkQueue _selectItemQueue; public NavigationBarController( IThreadingContext threadingContext, INavigationBarPresenter presenter, ITextBuffer subjectBuffer, IUIThreadOperationExecutor uiThreadOperationExecutor, IAsynchronousOperationListener asyncListener) : base(threadingContext) { _presenter = presenter; _subjectBuffer = subjectBuffer; _uiThreadOperationExecutor = uiThreadOperationExecutor; _asyncListener = asyncListener; _computeModelQueue = new AsyncBatchingWorkQueue<bool, NavigationBarModel>( TimeSpan.FromMilliseconds(TaggerConstants.ShortDelay), ComputeModelAndSelectItemAsync, EqualityComparer<bool>.Default, asyncListener, _cancellationTokenSource.Token); _selectItemQueue = new AsyncBatchingWorkQueue( TimeSpan.FromMilliseconds(TaggerConstants.NearImmediateDelay), SelectItemAsync, asyncListener, _cancellationTokenSource.Token); presenter.CaretMoved += OnCaretMoved; presenter.ViewFocused += OnViewFocused; presenter.DropDownFocused += OnDropDownFocused; presenter.ItemSelected += OnItemSelected; // Initialize the tasks to be an empty model so we never have to deal with a null case. _latestModelAndSelectedInfo_OnlyAccessOnUIThread.model = new(ImmutableArray<NavigationBarItem>.Empty, itemService: null!); _latestModelAndSelectedInfo_OnlyAccessOnUIThread.selectedInfo = new(typeItem: null, memberItem: null); // Use 'compilation available' as that may produce different results from the initial 'frozen partial' // snapshot we use. _eventSource = new CompilationAvailableTaggerEventSource( subjectBuffer, asyncListener, // Any time an edit happens, recompute as the nav bar items may have changed. TaggerEventSources.OnTextChanged(subjectBuffer), // Switching what is the active context may change the nav bar contents. TaggerEventSources.OnDocumentActiveContextChanged(subjectBuffer), // Many workspace changes may need us to change the items (like options changing, or project renaming). TaggerEventSources.OnWorkspaceChanged(subjectBuffer, asyncListener), // Once we hook this buffer up to the workspace, then we can start computing the nav bar items. TaggerEventSources.OnWorkspaceRegistrationChanged(subjectBuffer)); _eventSource.Changed += OnEventSourceChanged; _eventSource.Connect(); // Kick off initial work to populate the navbars StartModelUpdateAndSelectedItemUpdateTasks(); } private void OnEventSourceChanged(object? sender, TaggerEventArgs e) { StartModelUpdateAndSelectedItemUpdateTasks(); } void IDisposable.Dispose() { AssertIsForeground(); _presenter.CaretMoved -= OnCaretMoved; _presenter.ViewFocused -= OnViewFocused; _presenter.DropDownFocused -= OnDropDownFocused; _presenter.ItemSelected -= OnItemSelected; _presenter.Disconnect(); _eventSource.Changed -= OnEventSourceChanged; _eventSource.Disconnect(); _disconnected = true; // Cancel off any remaining background work _cancellationTokenSource.Cancel(); } private void StartModelUpdateAndSelectedItemUpdateTasks() { // If we disconnected already, just disregard if (_disconnected) return; // 'true' value is unused. this just signals to the queue that we have work to do. _computeModelQueue.AddWork(true); } private void OnCaretMoved(object? sender, EventArgs e) { AssertIsForeground(); StartSelectedItemUpdateTask(); } private void OnViewFocused(object? sender, EventArgs e) { AssertIsForeground(); StartSelectedItemUpdateTask(); } private void OnDropDownFocused(object? sender, EventArgs e) { AssertIsForeground(); var document = _subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) return; // Grab and present whatever information we have at this point. GetProjectItems(out var projectItems, out var selectedProjectItem); var (model, selectedInfo) = _latestModelAndSelectedInfo_OnlyAccessOnUIThread; if (Equals(model, _lastPresentedInfo.model) && Equals(selectedInfo, _lastPresentedInfo.selectedInfo) && Equals(selectedProjectItem, _lastPresentedInfo.selectedProjectItem) && projectItems.SequenceEqual(_lastPresentedInfo.projectItems)) { // Nothing changed, so we can skip presenting these items. return; } _presenter.PresentItems( projectItems, selectedProjectItem, model.Types, selectedInfo.TypeItem, selectedInfo.MemberItem); _lastPresentedInfo = (projectItems, selectedProjectItem, model, selectedInfo); } private void GetProjectItems(out ImmutableArray<NavigationBarProjectItem> projectItems, out NavigationBarProjectItem? selectedProjectItem) { var documents = _subjectBuffer.CurrentSnapshot.GetRelatedDocumentsWithChanges(); if (!documents.Any()) { projectItems = ImmutableArray<NavigationBarProjectItem>.Empty; selectedProjectItem = null; return; } projectItems = documents.Select(d => new NavigationBarProjectItem( d.Project.Name, d.Project.GetGlyph(), workspace: d.Project.Solution.Workspace, documentId: d.Id, language: d.Project.Language)).OrderBy(projectItem => projectItem.Text).ToImmutableArray(); var document = _subjectBuffer.AsTextContainer().GetOpenDocumentInCurrentContext(); selectedProjectItem = document != null ? projectItems.FirstOrDefault(p => p.Text == document.Project.Name) ?? projectItems.First() : projectItems.First(); } private void PushSelectedItemsToPresenter(NavigationBarSelectedTypeAndMember selectedItems) { AssertIsForeground(); var oldLeft = selectedItems.TypeItem; var oldRight = selectedItems.MemberItem; NavigationBarItem? newLeft = null; NavigationBarItem? newRight = null; using var _1 = ArrayBuilder<NavigationBarItem>.GetInstance(out var listOfLeft); using var _2 = ArrayBuilder<NavigationBarItem>.GetInstance(out var listOfRight); if (oldRight != null) { newRight = new NavigationBarPresentedItem( oldRight.Text, oldRight.Glyph, oldRight.TrackingSpans, oldRight.NavigationTrackingSpan, oldRight.ChildItems, oldRight.Bolded, oldRight.Grayed || selectedItems.ShowMemberItemGrayed); listOfRight.Add(newRight); } if (oldLeft != null) { newLeft = new NavigationBarPresentedItem( oldLeft.Text, oldLeft.Glyph, oldLeft.TrackingSpans, oldLeft.NavigationTrackingSpan, listOfRight.ToImmutable(), oldLeft.Bolded, oldLeft.Grayed || selectedItems.ShowTypeItemGrayed); listOfLeft.Add(newLeft); } GetProjectItems(out var projectItems, out var selectedProjectItem); _presenter.PresentItems( projectItems, selectedProjectItem, listOfLeft.ToImmutable(), newLeft, newRight); } private void OnItemSelected(object? sender, NavigationBarItemSelectedEventArgs e) { AssertIsForeground(); var token = _asyncListener.BeginAsyncOperation(nameof(OnItemSelected)); var task = OnItemSelectedAsync(e.Item); _ = task.CompletesAsyncOperation(token); } private async Task OnItemSelectedAsync(NavigationBarItem item) { AssertIsForeground(); using var waitContext = _uiThreadOperationExecutor.BeginExecute( EditorFeaturesResources.Navigation_Bars, EditorFeaturesResources.Refreshing_navigation_bars, allowCancellation: true, showProgress: false); try { await ProcessItemSelectionAsync(item, waitContext.UserCancellationToken).ConfigureAwait(false); } catch (OperationCanceledException) { } catch (Exception e) when (FatalError.ReportAndCatch(e)) { } } /// <summary> /// Process the selection of an item synchronously inside a wait context. /// </summary> /// <param name="item">The selected item.</param> /// <param name="cancellationToken">A cancellation token from the wait context.</param> private async Task ProcessItemSelectionAsync(NavigationBarItem item, CancellationToken cancellationToken) { AssertIsForeground(); if (item is NavigationBarPresentedItem) { // Presented items are not navigable, but they may be selected due to a race // documented in Bug #1174848. Protect all INavigationBarItemService implementers // from this by ignoring these selections here. return; } if (item is NavigationBarProjectItem projectItem) { projectItem.SwitchToContext(); } else { // When navigating, just use the partial semantics workspace. Navigation doesn't need the fully bound // compilations to be created, and it can save us a lot of costly time building skeleton assemblies. var document = _subjectBuffer.CurrentSnapshot.AsText().GetDocumentWithFrozenPartialSemantics(cancellationToken); if (document != null) { var navBarService = document.GetRequiredLanguageService<INavigationBarItemService>(); var snapshot = _subjectBuffer.CurrentSnapshot; var view = _presenter.TryGetCurrentView(); // ConfigureAwait(true) as we have to come back to UI thread in order to kick of the refresh task // below. Note that we only want to refresh if selecting the item had an effect (either navigating // or generating). If nothing happened to don't want to refresh. This is important as some items // exist in the type list that are only there to show a set a particular set of items in the member // list. So selecting such an item should only update the member list, and we do not want a refresh // to wipe that out. if (!await navBarService.TryNavigateToItemAsync(document, item, view, snapshot, cancellationToken).ConfigureAwait(true)) return; } } // Now that the edit has been done, refresh to make sure everything is up-to-date. StartModelUpdateAndSelectedItemUpdateTasks(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Implementation.Classification; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Tagging; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Tagging; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; using IUIThreadOperationExecutor = Microsoft.VisualStudio.Utilities.IUIThreadOperationExecutor; namespace Microsoft.CodeAnalysis.Editor.Implementation.NavigationBar { /// <summary> /// The controller for navigation bars. /// </summary> /// <remarks> /// The threading model for this class is simple: all non-static members are affinitized to the /// UI thread. /// </remarks> internal partial class NavigationBarController : ForegroundThreadAffinitizedObject, IDisposable { private readonly INavigationBarPresenter _presenter; private readonly ITextBuffer _subjectBuffer; private readonly IUIThreadOperationExecutor _uiThreadOperationExecutor; private readonly IAsynchronousOperationListener _asyncListener; private bool _disconnected = false; /// <summary> /// Latest model and selected items produced once <see cref="SelectItemAsync"/> completes and presents the /// single item to the view. These can then be read in when the dropdown is expanded and we want to show all /// items. /// </summary> private (NavigationBarModel model, NavigationBarSelectedTypeAndMember selectedInfo) _latestModelAndSelectedInfo_OnlyAccessOnUIThread; /// <summary> /// The last full information we have presented. If we end up wanting to present the same thing again, we can /// just skip doing that as the UI will already know about this. /// </summary> private (ImmutableArray<NavigationBarProjectItem> projectItems, NavigationBarProjectItem? selectedProjectItem, NavigationBarModel model, NavigationBarSelectedTypeAndMember selectedInfo) _lastPresentedInfo; /// <summary> /// Source of events that should cause us to update the nav bar model with new information. /// </summary> private readonly ITaggerEventSource _eventSource; private readonly CancellationTokenSource _cancellationTokenSource = new(); /// <summary> /// Queue to batch up work to do to compute the current model. Used so we can batch up a lot of events and only /// compute the model once for every batch. The <c>bool</c> type parameter isn't used, but is provided as this /// type is generic. /// </summary> private readonly AsyncBatchingWorkQueue<bool, NavigationBarModel> _computeModelQueue; /// <summary> /// Queue to batch up work to do to determine the selected item. Used so we can batch up a lot of events and /// only compute the selected item once for every batch. /// </summary> private readonly AsyncBatchingWorkQueue _selectItemQueue; public NavigationBarController( IThreadingContext threadingContext, INavigationBarPresenter presenter, ITextBuffer subjectBuffer, IUIThreadOperationExecutor uiThreadOperationExecutor, IAsynchronousOperationListener asyncListener) : base(threadingContext) { _presenter = presenter; _subjectBuffer = subjectBuffer; _uiThreadOperationExecutor = uiThreadOperationExecutor; _asyncListener = asyncListener; _computeModelQueue = new AsyncBatchingWorkQueue<bool, NavigationBarModel>( TimeSpan.FromMilliseconds(TaggerConstants.ShortDelay), ComputeModelAndSelectItemAsync, EqualityComparer<bool>.Default, asyncListener, _cancellationTokenSource.Token); _selectItemQueue = new AsyncBatchingWorkQueue( TimeSpan.FromMilliseconds(TaggerConstants.NearImmediateDelay), SelectItemAsync, asyncListener, _cancellationTokenSource.Token); presenter.CaretMoved += OnCaretMoved; presenter.ViewFocused += OnViewFocused; presenter.DropDownFocused += OnDropDownFocused; presenter.ItemSelected += OnItemSelected; // Initialize the tasks to be an empty model so we never have to deal with a null case. _latestModelAndSelectedInfo_OnlyAccessOnUIThread.model = new(ImmutableArray<NavigationBarItem>.Empty, itemService: null!); _latestModelAndSelectedInfo_OnlyAccessOnUIThread.selectedInfo = new(typeItem: null, memberItem: null); // Use 'compilation available' as that may produce different results from the initial 'frozen partial' // snapshot we use. _eventSource = new CompilationAvailableTaggerEventSource( subjectBuffer, asyncListener, // Any time an edit happens, recompute as the nav bar items may have changed. TaggerEventSources.OnTextChanged(subjectBuffer), // Switching what is the active context may change the nav bar contents. TaggerEventSources.OnDocumentActiveContextChanged(subjectBuffer), // Many workspace changes may need us to change the items (like options changing, or project renaming). TaggerEventSources.OnWorkspaceChanged(subjectBuffer, asyncListener), // Once we hook this buffer up to the workspace, then we can start computing the nav bar items. TaggerEventSources.OnWorkspaceRegistrationChanged(subjectBuffer)); _eventSource.Changed += OnEventSourceChanged; _eventSource.Connect(); // Kick off initial work to populate the navbars StartModelUpdateAndSelectedItemUpdateTasks(); } private void OnEventSourceChanged(object? sender, TaggerEventArgs e) { StartModelUpdateAndSelectedItemUpdateTasks(); } void IDisposable.Dispose() { AssertIsForeground(); _presenter.CaretMoved -= OnCaretMoved; _presenter.ViewFocused -= OnViewFocused; _presenter.DropDownFocused -= OnDropDownFocused; _presenter.ItemSelected -= OnItemSelected; _presenter.Disconnect(); _eventSource.Changed -= OnEventSourceChanged; _eventSource.Disconnect(); _disconnected = true; // Cancel off any remaining background work _cancellationTokenSource.Cancel(); } private void StartModelUpdateAndSelectedItemUpdateTasks() { // If we disconnected already, just disregard if (_disconnected) return; // 'true' value is unused. this just signals to the queue that we have work to do. _computeModelQueue.AddWork(true); } private void OnCaretMoved(object? sender, EventArgs e) { AssertIsForeground(); StartSelectedItemUpdateTask(); } private void OnViewFocused(object? sender, EventArgs e) { AssertIsForeground(); StartSelectedItemUpdateTask(); } private void OnDropDownFocused(object? sender, EventArgs e) { AssertIsForeground(); var document = _subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) return; // Grab and present whatever information we have at this point. GetProjectItems(out var projectItems, out var selectedProjectItem); var (model, selectedInfo) = _latestModelAndSelectedInfo_OnlyAccessOnUIThread; if (Equals(model, _lastPresentedInfo.model) && Equals(selectedInfo, _lastPresentedInfo.selectedInfo) && Equals(selectedProjectItem, _lastPresentedInfo.selectedProjectItem) && projectItems.SequenceEqual(_lastPresentedInfo.projectItems)) { // Nothing changed, so we can skip presenting these items. return; } _presenter.PresentItems( projectItems, selectedProjectItem, model.Types, selectedInfo.TypeItem, selectedInfo.MemberItem); _lastPresentedInfo = (projectItems, selectedProjectItem, model, selectedInfo); } private void GetProjectItems(out ImmutableArray<NavigationBarProjectItem> projectItems, out NavigationBarProjectItem? selectedProjectItem) { var documents = _subjectBuffer.CurrentSnapshot.GetRelatedDocumentsWithChanges(); if (!documents.Any()) { projectItems = ImmutableArray<NavigationBarProjectItem>.Empty; selectedProjectItem = null; return; } projectItems = documents.Select(d => new NavigationBarProjectItem( d.Project.Name, d.Project.GetGlyph(), workspace: d.Project.Solution.Workspace, documentId: d.Id, language: d.Project.Language)).OrderBy(projectItem => projectItem.Text).ToImmutableArray(); var document = _subjectBuffer.AsTextContainer().GetOpenDocumentInCurrentContext(); selectedProjectItem = document != null ? projectItems.FirstOrDefault(p => p.Text == document.Project.Name) ?? projectItems.First() : projectItems.First(); } private void PushSelectedItemsToPresenter(NavigationBarSelectedTypeAndMember selectedItems) { AssertIsForeground(); var oldLeft = selectedItems.TypeItem; var oldRight = selectedItems.MemberItem; NavigationBarItem? newLeft = null; NavigationBarItem? newRight = null; using var _1 = ArrayBuilder<NavigationBarItem>.GetInstance(out var listOfLeft); using var _2 = ArrayBuilder<NavigationBarItem>.GetInstance(out var listOfRight); if (oldRight != null) { newRight = new NavigationBarPresentedItem( oldRight.Text, oldRight.Glyph, oldRight.TrackingSpans, oldRight.NavigationTrackingSpan, oldRight.ChildItems, oldRight.Bolded, oldRight.Grayed || selectedItems.ShowMemberItemGrayed); listOfRight.Add(newRight); } if (oldLeft != null) { newLeft = new NavigationBarPresentedItem( oldLeft.Text, oldLeft.Glyph, oldLeft.TrackingSpans, oldLeft.NavigationTrackingSpan, listOfRight.ToImmutable(), oldLeft.Bolded, oldLeft.Grayed || selectedItems.ShowTypeItemGrayed); listOfLeft.Add(newLeft); } GetProjectItems(out var projectItems, out var selectedProjectItem); _presenter.PresentItems( projectItems, selectedProjectItem, listOfLeft.ToImmutable(), newLeft, newRight); } private void OnItemSelected(object? sender, NavigationBarItemSelectedEventArgs e) { AssertIsForeground(); var token = _asyncListener.BeginAsyncOperation(nameof(OnItemSelected)); var task = OnItemSelectedAsync(e.Item); _ = task.CompletesAsyncOperation(token); } private async Task OnItemSelectedAsync(NavigationBarItem item) { AssertIsForeground(); using var waitContext = _uiThreadOperationExecutor.BeginExecute( EditorFeaturesResources.Navigation_Bars, EditorFeaturesResources.Refreshing_navigation_bars, allowCancellation: true, showProgress: false); try { await ProcessItemSelectionAsync(item, waitContext.UserCancellationToken).ConfigureAwait(false); } catch (OperationCanceledException) { } catch (Exception e) when (FatalError.ReportAndCatch(e)) { } } /// <summary> /// Process the selection of an item synchronously inside a wait context. /// </summary> /// <param name="item">The selected item.</param> /// <param name="cancellationToken">A cancellation token from the wait context.</param> private async Task ProcessItemSelectionAsync(NavigationBarItem item, CancellationToken cancellationToken) { AssertIsForeground(); if (item is NavigationBarPresentedItem) { // Presented items are not navigable, but they may be selected due to a race // documented in Bug #1174848. Protect all INavigationBarItemService implementers // from this by ignoring these selections here. return; } if (item is NavigationBarProjectItem projectItem) { projectItem.SwitchToContext(); } else { // When navigating, just use the partial semantics workspace. Navigation doesn't need the fully bound // compilations to be created, and it can save us a lot of costly time building skeleton assemblies. var document = _subjectBuffer.CurrentSnapshot.AsText().GetDocumentWithFrozenPartialSemantics(cancellationToken); if (document != null) { var navBarService = document.GetRequiredLanguageService<INavigationBarItemService>(); var snapshot = _subjectBuffer.CurrentSnapshot; var view = _presenter.TryGetCurrentView(); // ConfigureAwait(true) as we have to come back to UI thread in order to kick of the refresh task // below. Note that we only want to refresh if selecting the item had an effect (either navigating // or generating). If nothing happened to don't want to refresh. This is important as some items // exist in the type list that are only there to show a set a particular set of items in the member // list. So selecting such an item should only update the member list, and we do not want a refresh // to wipe that out. if (!await navBarService.TryNavigateToItemAsync(document, item, view, snapshot, cancellationToken).ConfigureAwait(true)) return; } } // Now that the edit has been done, refresh to make sure everything is up-to-date. StartModelUpdateAndSelectedItemUpdateTasks(); } } }
-1
dotnet/roslyn
55,409
Use FixedSize API
tmat
2021-08-04T19:30:40Z
2021-08-04T21:53:46Z
e0112742bff208dd0546de45e36f7b52058a45a3
c90bf0ec986010051662c8e1fbc872c2fd86bc4e
Use FixedSize API.
./src/Compilers/CSharp/Portable/BoundTree/BoundDagRelationalTest.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class BoundDagRelationalTest { public BinaryOperatorKind Relation => OperatorKind.Operator(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class BoundDagRelationalTest { public BinaryOperatorKind Relation => OperatorKind.Operator(); } }
-1
dotnet/roslyn
55,409
Use FixedSize API
tmat
2021-08-04T19:30:40Z
2021-08-04T21:53:46Z
e0112742bff208dd0546de45e36f7b52058a45a3
c90bf0ec986010051662c8e1fbc872c2fd86bc4e
Use FixedSize API.
./src/EditorFeatures/VisualBasicTest/InlineMethod/VisualBasicInlineMethodTests.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.Editor.UnitTests.CodeActions Imports Microsoft.CodeAnalysis.Testing Imports Microsoft.CodeAnalysis.VisualBasic.CodeRefactorings.InlineTemporary Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.InlineMethod <Trait(Traits.Feature, Traits.Features.CodeActionsInlineMethod)> Public Class VisualBasicInlineMethodTests Private Class TestVerifier Inherits VisualBasicCodeRefactoringVerifier(Of VisualBasicInlineMethodRefactoringProvider).Test Private Const Marker As String = "##" Public Shared Async Function TestInRegularAndScriptInDifferentFilesAsync( initialMarkUpForFile1 As String, initialMarkUpForFile2 As String, expectedMarkUpForFile1 As String, expectedMarkUpForFile2 As String, diagnosticResults As List(Of DiagnosticResult), Optional keepInlinedMethod As Boolean = True) As Task Dim test = New TestVerifier() With { .CodeActionIndex = If(keepInlinedMethod, 1, 0), .CodeActionValidationMode = CodeActionValidationMode.None } test.TestState.Sources.Add(("File1", initialMarkUpForFile1)) test.TestState.Sources.Add(("File2", initialMarkUpForFile2)) test.FixedState.Sources.Add(("File1", expectedMarkUpForFile1)) test.FixedState.Sources.Add(("File2", expectedMarkUpForFile2)) If diagnosticResults IsNot Nothing Then test.FixedState.ExpectedDiagnostics.AddRange(diagnosticResults) End If Await test.RunAsync().ConfigureAwait(False) End Function Public Shared Async Function TestInRegularAndScriptAsync( initialMarkUp As String, expectedMarkUp As String, Optional diagnnoticResults As List(Of DiagnosticResult) = Nothing, Optional keepInlinedMethod As Boolean = True) As Task Dim test As New TestVerifier() With {.CodeActionIndex = If(keepInlinedMethod, 1, 0), .CodeActionValidationMode = CodeActionValidationMode.None} test.TestState.Sources.Add(initialMarkUp) test.FixedState.Sources.Add(expectedMarkUp) If diagnnoticResults IsNot Nothing Then test.FixedState.ExpectedDiagnostics.AddRange(diagnnoticResults) End If Await test.RunAsync().ConfigureAwait(False) End Function Public Shared Async Function TestBothKeepAndRemoveInlinedMethodAsync( initialMarkUp As String, expectedMarkUp As String, Optional diagnnoticResultsWhenKeepInlinedMethod As List(Of DiagnosticResult) = Nothing, Optional diagnnoticResultsWhenRemoveInlinedMethod As List(Of DiagnosticResult) = Nothing) As Task Dim firstMarkerIndex = expectedMarkUp.IndexOf(Marker) Dim secondMarkerIndex = expectedMarkUp.LastIndexOf(Marker) If firstMarkerIndex = -1 OrElse secondMarkerIndex = 1 OrElse firstMarkerIndex = secondMarkerIndex Then Assert.True(False, "Can't find proper marks that contains inlined method.") End If Dim firstPartitionBeforeMarkUp = expectedMarkUp.Substring(0, firstMarkerIndex) Dim inlinedMethod = expectedMarkUp.Substring(firstMarkerIndex + 2, secondMarkerIndex - firstMarkerIndex - 2) Dim lastPartitionAfterMarkup = expectedMarkUp.Substring(secondMarkerIndex + 2) Await TestInRegularAndScriptAsync(initialMarkUp, String.Concat(firstPartitionBeforeMarkUp, inlinedMethod, lastPartitionAfterMarkup), diagnnoticResultsWhenKeepInlinedMethod, keepInlinedMethod:=True).ConfigureAwait(False) Await TestInRegularAndScriptAsync(initialMarkUp, String.Concat(firstPartitionBeforeMarkUp, lastPartitionAfterMarkup), diagnnoticResultsWhenRemoveInlinedMethod, keepInlinedMethod:=False).ConfigureAwait(False) End Function Public Shared Async Function TestBothKeepAndRemoveInlinedMethodInDifferentFileAsync( initialMarkUpForCaller As String, initialMarkUpForCallee As String, expectedMarkUpForCaller As String, expectedMarkUpForCallee As String, Optional diagnosticResultsWhenKeepInlinedMethod As List(Of DiagnosticResult) = Nothing, Optional diagnosticResultsWhenRemoveInlinedMethod As List(Of DiagnosticResult) = Nothing) As Task Dim firstMarkerIndex = expectedMarkUpForCallee.IndexOf(Marker) Dim secondMarkerIndex = expectedMarkUpForCallee.LastIndexOf(Marker) If firstMarkerIndex = -1 OrElse secondMarkerIndex = -1 OrElse firstMarkerIndex = secondMarkerIndex Then Assert.True(False, "Can't find proper marks that contains inlined method.") End If Dim firstPartitionBeforeMarkUp = expectedMarkUpForCallee.Substring(0, firstMarkerIndex) Dim inlinedMethod = expectedMarkUpForCallee.Substring(firstMarkerIndex + 2, secondMarkerIndex - firstMarkerIndex - 2) Dim lastPartitionAfterMarkup = expectedMarkUpForCallee.Substring(secondMarkerIndex + 2) Await TestInRegularAndScriptInDifferentFilesAsync( initialMarkUpForCaller, initialMarkUpForCallee, expectedMarkUpForCaller, String.Concat(firstPartitionBeforeMarkUp, inlinedMethod, lastPartitionAfterMarkup), diagnosticResultsWhenKeepInlinedMethod, keepInlinedMethod:=True).ConfigureAwait(False) Await TestInRegularAndScriptInDifferentFilesAsync( initialMarkUpForCaller, initialMarkUpForCallee, expectedMarkUpForCaller, String.Concat(firstPartitionBeforeMarkUp, lastPartitionAfterMarkup), diagnosticResultsWhenRemoveInlinedMethod, keepInlinedMethod:=False).ConfigureAwait(False) End Function End Class <Fact> Public Function TestInlineExpressionStatement() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Class TestClass Public Sub Caller(i As Integer) Me.Ca[||]llee(i) End Sub Private Sub Callee(i As Integer) System.Console.WriteLine(i) End Sub End Class", " Public Class TestClass Public Sub Caller(i As Integer) System.Console.WriteLine(i) End Sub ## Private Sub Callee(i As Integer) System.Console.WriteLine(i) End Sub ##End Class") End Function <Fact> Public Function TestInlineExpressionStatementInDifferentFiles() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodInDifferentFileAsync(" Partial Public Class TestClass Public Sub Caller(i As Integer) Me.Ca[||]llee(i) End Sub End Class", " Partial Public Class TestClass Private Sub Callee(i As Integer) System.Console.WriteLine(i) End Sub End Class", " Partial Public Class TestClass Public Sub Caller(i As Integer) System.Console.WriteLine(i) End Sub End Class", " Partial Public Class TestClass ## Private Sub Callee(i As Integer) System.Console.WriteLine(i) End Sub ##End Class") End Function <Fact> Public Function TestInlineReturnExpression() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Class TestClass Public Sub Caller(i As Integer) Dim x = Me.Ca[||]llee(i) End Sub Private Function Callee(i As Integer) As Integer Return i + 10 End Function End Class", " Public Class TestClass Public Sub Caller(i As Integer) Dim x = i + 10 End Sub ## Private Function Callee(i As Integer) As Integer Return i + 10 End Function ##End Class") End Function <Fact> Public Function TestInlineDefaultValue() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Enum A Value1 Value2 End Enum Public Class TestClass Public Sub Caller() Ca[||]llee() End Sub Private Function Callee(Optional i As Integer = 20, Optional b As Boolean = False, Optional c As A = Nothing) As Integer Return i + If(b, 10, 100) + CType(c, Integer) End Function End Class", " Public Enum A Value1 Value2 End Enum Public Class TestClass Public Sub Caller() Dim temp As Integer = 20 + If(False, 10, 100) + CType(A.Value1, Integer) End Sub ## Private Function Callee(Optional i As Integer = 20, Optional b As Boolean = False, Optional c As A = Nothing) As Integer Return i + If(b, 10, 100) + CType(c, Integer) End Function ##End Class") End Function <Fact> Public Function TestInlineGenerics1() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Class TestClass Public Sub Caller() Ca[||]llee(Of Integer)() End Sub Private Function Callee(Of T)() As String Return GetType(T).ToString() End Function End Class", " Public Class TestClass Public Sub Caller() GetType(Integer).ToString() End Sub ## Private Function Callee(Of T)() As String Return GetType(T).ToString() End Function ##End Class") End Function <Fact> Public Function TestInlineGenerics1InDifferenceFiles() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodInDifferentFileAsync(" Partial Public Class TestClass Public Sub Caller() Ca[||]llee(Of Integer)() End Sub End Class", " Partial Public Class TestClass Private Function Callee(Of T)() As String Return GetType(T).ToString() End Function End Class", " Partial Public Class TestClass Public Sub Caller() GetType(Integer).ToString() End Sub End Class", " Partial Public Class TestClass ## Private Function Callee(Of T)() As String Return GetType(T).ToString() End Function ##End Class") End Function <Fact> Public Function TestInlineGenerics2() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Class TestClass Public Sub Caller() Ca[||]llee(1) End Sub Private Function Callee(Of T)(i As T) As String Return GetType(T).ToString() End Function End Class", " Public Class TestClass Public Sub Caller() GetType(Integer).ToString() End Sub ## Private Function Callee(Of T)(i As T) As String Return GetType(T).ToString() End Function ##End Class") End Function <Fact> Public Function TestInlineWithAddAndMultiple() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Class TestClass Public Sub Caller(i As Integer, j As Integer) Dim x = 1 * Ca[||]llee(i, j) End Sub Private Function Callee(a As Integer, b As Integer) As Integer Return a + b End Function End Class", " Public Class TestClass Public Sub Caller(i As Integer, j As Integer) Dim x = 1 * (i + j) End Sub ## Private Function Callee(a As Integer, b As Integer) As Integer Return a + b End Function ##End Class") End Function <Fact> Public Function TestInlineDefaultValueInDifferentFile() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodInDifferentFileAsync(" Public Enum A Value1 Value2 End Enum Partial Public Class TestClass Public Sub Caller() Ca[||]llee() End Sub End Class", " Partial Public Class TestClass Private Function Callee(Optional i As Integer = 20, Optional b As Boolean = False, Optional c As A = Nothing) As Integer Return i + If(b, 10, 100) + CType(c, Integer) End Function End Class", " Public Enum A Value1 Value2 End Enum Partial Public Class TestClass Public Sub Caller() Dim temp As Integer = 20 + If(False, 10, 100) + CType(A.Value1, Integer) End Sub End Class", " Partial Public Class TestClass ## Private Function Callee(Optional i As Integer = 20, Optional b As Boolean = False, Optional c As A = Nothing) As Integer Return i + If(b, 10, 100) + CType(c, Integer) End Function ##End Class") End Function <Fact> Public Function TestInlineWithLiteralValue() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Enum A Value1 Value2 End Enum Public Class TestClass Public Sub Caller() Ca[||]llee(1, True, A.Value2) End Sub Private Function Callee(Optional i As Integer = 20, Optional b As Boolean = False, Optional c As A = Nothing) As Integer Return i + If(b, 10, 100) + CType(c, Integer) End Function End Class", " Public Enum A Value1 Value2 End Enum Public Class TestClass Public Sub Caller() Dim temp As Integer = 1 + If(True, 10, 100) + CType(A.Value2, Integer) End Sub ## Private Function Callee(Optional i As Integer = 20, Optional b As Boolean = False, Optional c As A = Nothing) As Integer Return i + If(b, 10, 100) + CType(c, Integer) End Function ##End Class") End Function <Fact> Public Function TestInlineWithLiteralValueInDifferentFile() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodInDifferentFileAsync(" Public Enum A Value1 Value2 End Enum Partial Public Class TestClass Public Sub Caller() Ca[||]llee(1, True, A.Value2) End Sub End Class", " Partial Public Class TestClass Private Function Callee(Optional i As Integer = 20, Optional b As Boolean = False, Optional c As A = Nothing) As Integer Return i + If(b, 10, 100) + CType(c, Integer) End Function End Class", " Public Enum A Value1 Value2 End Enum Partial Public Class TestClass Public Sub Caller() Dim temp As Integer = 1 + If(True, 10, 100) + CType(A.Value2, Integer) End Sub End Class", " Partial Public Class TestClass ## Private Function Callee(Optional i As Integer = 20, Optional b As Boolean = False, Optional c As A = Nothing) As Integer Return i + If(b, 10, 100) + CType(c, Integer) End Function ##End Class") End Function <Fact> Public Function TestInlineWithIdentifierReplacement() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Enum A Value1 Value2 End Enum Public Class TestClass Public Sub Caller(c As A) Dim a = 10 Dim b = True Ca[||]llee(a, b, c) End Sub Private Function Callee(Optional i As Integer = 20, Optional b As Boolean = False, Optional c As A = Nothing) As Integer Return i + If(b, 10, 100) + CType(c, Integer) End Function End Class", " Public Enum A Value1 Value2 End Enum Public Class TestClass Public Sub Caller(c As A) Dim a = 10 Dim b = True Dim temp As Integer = a + If(b, 10, 100) + CType(c, Integer) End Sub ## Private Function Callee(Optional i As Integer = 20, Optional b As Boolean = False, Optional c As A = Nothing) As Integer Return i + If(b, 10, 100) + CType(c, Integer) End Function ##End Class") End Function <Fact> Public Function TestInlineWithIdentifierReplacementInDifferentFile() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodInDifferentFileAsync(" Public Enum A Value1 Value2 End Enum Partial Public Class TestClass Public Sub Caller(c As A) Dim a = 10 Dim b = True Ca[||]llee(a, b, c) End Sub End Class", " Partial Public Class TestClass Private Function Callee(Optional i As Integer = 20, Optional b As Boolean = False, Optional c As A = Nothing) As Integer Return i + If(b, 10, 100) + CType(c, Integer) End Function End Class", " Public Enum A Value1 Value2 End Enum Partial Public Class TestClass Public Sub Caller(c As A) Dim a = 10 Dim b = True Dim temp As Integer = a + If(b, 10, 100) + CType(c, Integer) End Sub End Class", " Partial Public Class TestClass ## Private Function Callee(Optional i As Integer = 20, Optional b As Boolean = False, Optional c As A = Nothing) As Integer Return i + If(b, 10, 100) + CType(c, Integer) End Function ##End Class") End Function <Fact> Public Function TestInlineParamArray1() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync( " Public Class TestClass Public Sub Caller() Ca[||]llee(1, 2, 3, 4) End Sub Private Sub Callee(ParamArray args() as Integer) System.Console.WriteLine(args.Length) End Sub End Class", " Public Class TestClass Public Sub Caller() System.Console.WriteLine((New Integer() {1, 2, 3, 4}).Length) End Sub ## Private Sub Callee(ParamArray args() as Integer) System.Console.WriteLine(args.Length) End Sub ##End Class") End Function <Fact> Public Function TestInlineParamArray1InDifferentFile() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodInDifferentFileAsync(" Partial Public Class TestClass Public Sub Caller() Ca[||]llee(1, 2, 3, 4) End Sub End Class", " Partial Public Class TestClass Private Sub Callee(ParamArray args() as Integer) System.Console.WriteLine(args.Length) End Sub End Class", " Partial Public Class TestClass Public Sub Caller() System.Console.WriteLine((New Integer() {1, 2, 3, 4}).Length) End Sub End Class", " Partial Public Class TestClass ## Private Sub Callee(ParamArray args() as Integer) System.Console.WriteLine(args.Length) End Sub ##End Class") End Function <Fact> Public Function TestInlineParamArray2() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync( " Public Class TestClass Public Sub Caller() Ca[||]llee(New Integer() {1, 2, 3, 4}) End Sub Private Sub Callee(ParamArray args() as Integer) System.Console.WriteLine(args.Length) End Sub End Class", " Public Class TestClass Public Sub Caller() System.Console.WriteLine((New Integer() {1, 2, 3, 4}).Length) End Sub ## Private Sub Callee(ParamArray args() as Integer) System.Console.WriteLine(args.Length) End Sub ##End Class") End Function <Fact> Public Function TestInlineParamArray3() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync( " Public Class TestClass Public Sub Caller() Ca[||]llee(1) End Sub Private Sub Callee(ParamArray args() as Integer) System.Console.WriteLine(args.Length) End Sub End Class", " Public Class TestClass Public Sub Caller() System.Console.WriteLine((New Integer() {1}).Length) End Sub ## Private Sub Callee(ParamArray args() as Integer) System.Console.WriteLine(args.Length) End Sub ##End Class") End Function <Fact> Public Function TestInlineParamArray4() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync( " Public Class TestClass Public Sub Caller() Ca[||]llee() End Sub Private Sub Callee(ParamArray args() as Integer) System.Console.WriteLine(args.Length) End Sub End Class", " Public Class TestClass Public Sub Caller() System.Console.WriteLine((New Integer() {}).Length) End Sub ## Private Sub Callee(ParamArray args() as Integer) System.Console.WriteLine(args.Length) End Sub ##End Class") End Function <Fact> Public Function TestInlineParamArray5() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync( " Public Class TestClass Public Sub Caller() Ca[||]llee(1) End Sub Private Sub Callee(ParamArray args() as Integer) System.Console.WriteLine(args.Length) End Sub End Class", " Public Class TestClass Public Sub Caller() System.Console.WriteLine((New Integer() {1}).Length) End Sub ## Private Sub Callee(ParamArray args() as Integer) System.Console.WriteLine(args.Length) End Sub ##End Class") End Function <Fact> Public Function TestInlineSelf() As Task Return TestVerifier.TestInRegularAndScriptAsync(" Public Class TestClass Public Sub Caller(i As Integer) Callee(Callee(Ca[||]llee(i))) End Sub Private Function Callee(i As Integer) As Integer Return i + 10 End Function End Class", " Public Class TestClass Public Sub Caller(i As Integer) Callee(Callee(i + 10)) End Sub Private Function Callee(i As Integer) As Integer Return i + 10 End Function End Class") End Function <Fact> Public Function TestInlineWithLiteralArgument() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Class TestClass Public Sub Caller() Ca[||]llee(5, True) End Sub Private Function Callee(i As Integer, b As Boolean) As Integer Return i + If(b, 10, 100) End Function End Class", " Public Class TestClass Public Sub Caller() Dim temp As Integer = 5 + If(True, 10, 100) End Sub ## Private Function Callee(i As Integer, b As Boolean) As Integer Return i + If(b, 10, 100) End Function ##End Class") End Function <Fact> Public Function TestInlineIdentifierArgument() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Class TestClass Public Sub Caller() Dim i = 2222 Dim x = True Ca[||]llee(i, x) End Sub Private Function Callee(i As Integer, b As Boolean) As Integer Return i + If(b, 10, 100) End Function End Class", " Public Class TestClass Public Sub Caller() Dim i = 2222 Dim x = True Dim temp As Integer = i + If(x, 10, 100) End Sub ## Private Function Callee(i As Integer, b As Boolean) As Integer Return i + If(b, 10, 100) End Function ##End Class") End Function <Fact> Public Function TestInlineInOperator() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Class TestClass Public Shared Operator +(i As TestClass, j As TestClass) Ca[||]llee(10) Return Nothing End Operator Private Shared Sub Callee(i As Integer) System.Console.WriteLine(i) End Sub End Class", " Public Class TestClass Public Shared Operator +(i As TestClass, j As TestClass) System.Console.WriteLine(10) Return Nothing End Operator ## Private Shared Sub Callee(i As Integer) System.Console.WriteLine(i) End Sub ##End Class") End Function <Fact> Public Function TestIdentifierRename() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync( " Public Class TestClass Public Sub Caller(i As Integer, j As Integer) Dim x = Call[||]ee(Cal(i, j), Cal(i, j)) End Sub Private Function Callee(i As Integer, j As Integer) as Integer return i * j End Function Private Function Cal(i As Integer, j As Integer) As Integer Return i + j End Function End Class", " Public Class TestClass Public Sub Caller(i As Integer, j As Integer) Dim x = Cal(i, j) * Cal(i, j) End Sub ## Private Function Callee(i As Integer, j As Integer) as Integer return i * j End Function ## Private Function Cal(i As Integer, j As Integer) As Integer Return i + j End Function End Class") End Function <Fact> Public Function TestInlineLambda1() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync( " Imports System Public Class TestClass Public Sub Caller(i As Integer, j As Integer) Dim x = Call[||]ee(i, j)() End Sub Private Function Callee(i As Integer, j As Integer) as Func(Of Integer) return Function() Return i * j End Function End Function End Class", " Imports System Public Class TestClass Public Sub Caller(i As Integer, j As Integer) Dim x = Function() Return i * j End Function() End Sub ## Private Function Callee(i As Integer, j As Integer) as Func(Of Integer) return Function() Return i * j End Function End Function ##End Class") End Function <Fact> Public Function TestInlineLambda2() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync( " Imports System Public Class TestClass Public Sub Caller(i As Integer, j As Integer) Dim x = Call[||]ee(i, j)() End Sub Private Function Callee(i As Integer, j As Integer) as Func(Of Integer) return Function() i * j End Function End Class", " Imports System Public Class TestClass Public Sub Caller(i As Integer, j As Integer) Dim x = (Function() i * j)() End Sub ## Private Function Callee(i As Integer, j As Integer) as Func(Of Integer) return Function() i * j End Function ##End Class") End Function <Fact> Public Function TestInlineAwaitExpression1() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync( " Imports System.Threading.Tasks Public Class TestClass Public Function Caller() As Task Return Ca[||]llee() End Function Private Async Function Callee() As Task Await Task.Delay(100) End Function End Class", " Imports System.Threading.Tasks Public Class TestClass Public Function Caller() As Task Return Task.Delay(100) End Function ## Private Async Function Callee() As Task Await Task.Delay(100) End Function ##End Class") End Function <Fact> Public Function TestInlineAwaitExpression2() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync( " Imports System.Threading.Tasks Public Class TestClass Public Sub Caller() Dim x = Function(i As Integer) As Task Return Cal[||]lee() End Function End Sub Private Async Function Callee() As Task Await Task.Delay(100) End Function End Class", " Imports System.Threading.Tasks Public Class TestClass Public Sub Caller() Dim x = Function(i As Integer) As Task Return Task.Delay(100) End Function End Sub ## Private Async Function Callee() As Task Await Task.Delay(100) End Function ##End Class") End Function <Fact> Public Function TestInlineAwaitExpression3() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync( " Imports System.Threading.Tasks Public Class TestClass Public Async Function Caller() As Task Await Ca[||]llee() End Function Private Async Function Callee() As Task(Of Integer) Return Await Task.FromResult(1) End Function End Class", " Imports System.Threading.Tasks Public Class TestClass Public Async Function Caller() As Task Await Task.FromResult(1) End Function ## Private Async Function Callee() As Task(Of Integer) Return Await Task.FromResult(1) End Function ##End Class") End Function <Fact> Public Function TestInlineAwaitExpression4() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync( " Imports System.Threading.Tasks Public Class TestClass Public Function Caller() As Task Dim x = Ca[||]llee() End Function Private Async Function Callee() As Task(Of Integer) Return Await Task.FromResult(Await Task.FromResult(100)) End Function End Class", " Imports System.Threading.Tasks Public Class TestClass Public Async Function Caller() As Task Dim x = Task.FromResult(Await Task.FromResult(100)) End Function ## Private Async Function Callee() As Task(Of Integer) Return Await Task.FromResult(Await Task.FromResult(100)) End Function ##End Class") End Function <Fact> Public Function TestThrowStatement() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync( " Imports System Public Class TestClass Public Sub Caller() Ca[||]llee() End Sub Private Function Callee() As Integer Throw New Exception() End Function End Class", " Imports System Public Class TestClass Public Sub Caller() Throw New Exception() End Sub ## Private Function Callee() As Integer Throw New Exception() End Function ##End Class") End Function <Fact> Public Function TestInlineInConstructor() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Class TestClass Public Sub New(i As Integer) Me.Ca[||]llee(i) End Sub Private Sub Callee(i As Integer) System.Console.WriteLine(i) End Sub End Class", " Public Class TestClass Public Sub New(i As Integer) System.Console.WriteLine(i) End Sub ## Private Sub Callee(i As Integer) System.Console.WriteLine(i) End Sub ##End Class") End Function <Fact> Public Function TestInlineReturnExpressionWithoutVariableDeclaration() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Class TestClass Public Sub Caller(i As Integer) Me.Ca[||]llee(i) End Sub Private Function Callee(i As Integer) As Integer Return i + 10 End Function End Class", " Public Class TestClass Public Sub Caller(i As Integer) Dim temp As Integer = i + 10 End Sub ## Private Function Callee(i As Integer) As Integer Return i + 10 End Function ##End Class") End Function <Fact> Public Function TestInlineExpression1() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Class TestClass Public Sub Caller(i As Integer) Me.Ca[||]llee(i * 2) End Sub Private Function Callee(i As Integer) As Integer Return i + i End Function End Class", " Public Class TestClass Public Sub Caller(i As Integer) Dim i1 As Integer = i * 2 Dim temp As Integer = i1 + i1 End Sub ## Private Function Callee(i As Integer) As Integer Return i + i End Function ##End Class") End Function <Fact> Public Function TestInlineInSingleLineLambda() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Class TestClass Public Sub Caller(i As Integer) Dim f = Function() Call[||]ee(GetInt()) End Sub Private Function GetInt() As Integer Return 10 End Function Private Function Callee(i As Integer) As Integer Return i + i End Function End Class", " Public Class TestClass Public Sub Caller(i As Integer) Dim f = Function() GetInt() + GetInt() End Sub Private Function GetInt() As Integer Return 10 End Function ## Private Function Callee(i As Integer) As Integer Return i + i End Function ##End Class") End Function <Fact> Public Function TestInlineInMultiLineLambda() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Class TestClass Public Sub Caller(i As Integer) Dim f = Function() Return Call[||]ee(GetInt()) End Function End Sub Private Function GetInt() As Integer Return 10 End Function Private Function Callee(i As Integer) As Integer Return i + i End Function End Class", " Public Class TestClass Public Sub Caller(i As Integer) Dim f = Function() Dim i1 As Integer = GetInt() Return i1 + i1 End Function End Sub Private Function GetInt() As Integer Return 10 End Function ## Private Function Callee(i As Integer) As Integer Return i + i End Function ##End Class") End Function <Fact> Public Function TestInlineSimpleAssignment() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Class TestClass Public Sub Caller(i As Integer) Dim y As Integer = Call[||]ee(10) End Sub Private Function Callee(i As Integer) As Integer Return i = 100 End Function End Class", " Public Class TestClass Public Sub Caller(i As Integer) Dim y As Integer = 10 = 100 End Sub ## Private Function Callee(i As Integer) As Integer Return i = 100 End Function ##End Class") End Function <Fact> Public Function TestInlineInDoWhileStatement() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Class TestClass Public Sub Caller(i As Boolean) Do Loop While Ca[||]llee(GetFlag()) End Sub Private Function GetFlag() As Boolean Return True End Function Private Function Callee(a As Boolean) As Boolean Return a OrElse a End Function End Class", " Public Class TestClass Public Sub Caller(i As Boolean) Dim a As Boolean = GetFlag() Do Loop While a OrElse a End Sub Private Function GetFlag() As Boolean Return True End Function ## Private Function Callee(a As Boolean) As Boolean Return a OrElse a End Function ##End Class") End Function <Fact> Public Function TestInlineInWhileStatement() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Class TestClass Public Sub Caller(i As Boolean) While Ca[||]llee(GetFlag()) End While End Sub Private Function GetFlag() As Boolean Return True End Function Private Function Callee(a As Boolean) As Boolean Return a OrElse a End Function End Class", " Public Class TestClass Public Sub Caller(i As Boolean) Dim a As Boolean = GetFlag() While a OrElse a End While End Sub Private Function GetFlag() As Boolean Return True End Function ## Private Function Callee(a As Boolean) As Boolean Return a OrElse a End Function ##End Class") End Function <Fact> Public Function TestInlineInIfStatement() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Class TestClass Public Sub Caller(i As Boolean) If C[||]allee(GetFlag()) OrElse True Then End If End Sub Private Function GetFlag() As Boolean Return True End Function Private Function Callee(a As Boolean) As Boolean Return a OrElse a End Function End Class", " Public Class TestClass Public Sub Caller(i As Boolean) Dim a As Boolean = GetFlag() If a OrElse a OrElse True Then End If End Sub Private Function GetFlag() As Boolean Return True End Function ## Private Function Callee(a As Boolean) As Boolean Return a OrElse a End Function ##End Class") End Function <Fact> Public Function TestInlineWithinLockStatement() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Class TestClass Public Sub Caller() SyncLock Ca[||]llee(GetFlag()) End SyncLock End Sub Private Function GetFlag() As Integer Return 10 End Function Private Function Callee(a As Integer) As String Return (a + a).ToString() End Function End Class", " Public Class TestClass Public Sub Caller() Dim a As Integer = GetFlag() SyncLock (a + a).ToString() End SyncLock End Sub Private Function GetFlag() As Integer Return 10 End Function ## Private Function Callee(a As Integer) As String Return (a + a).ToString() End Function ##End Class") End Function <Fact> Public Function TestInlineConditionalExpression() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Class TestClass Public Sub Caller(i As Integer) Dim y = Call[||]ee(true) End Sub Private Function Callee(a As Boolean) As Integer Return If (a, 10, 100) End Function End Class", " Public Class TestClass Public Sub Caller(i As Integer) Dim y = If (true, 10, 100) End Sub ## Private Function Callee(a As Boolean) As Integer Return If (a, 10, 100) End Function ##End Class") End Function <Fact> Public Function TestInlineInInvocation() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Class TestClass Public Sub Caller(i As Integer) Callee(Ge[||]tInt()) End Sub Private Function Callee(i As Integer) As Integer Return i + i End Function Private Function GetInt() As Integer Return 10 End Function End Class", " Public Class TestClass Public Sub Caller(i As Integer) Callee(10) End Sub Private Function Callee(i As Integer) As Integer Return i + i End Function ## Private Function GetInt() As Integer Return 10 End Function ##End Class") End Function <Fact> Public Function TestExtensionMethod() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync( " Imports System.Runtime.CompilerServices Module TestModule Sub Main() Dim i = 1 Dim i2 = i.Ca[||]llee() End Sub <Extension()> Private Function Callee(i As Integer) As Integer Return i + 1 End Function End Module", " Imports System.Runtime.CompilerServices Module TestModule Sub Main() Dim i = 1 Dim i2 = i + 1 End Sub ## <Extension()> Private Function Callee(i As Integer) As Integer Return i + 1 End Function ##End Module") End Function <Fact> Public Function TestInlineInField() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Class TestClass Private TestField As Integer = Cal[||]lee(GetInt()) Private Shared Function GetInt() As Integer Return 10 End Function Private Shared Function Callee(i As Integer) As Integer Return i + i End Function End Class", " Public Class TestClass Private TestField As Integer = GetInt() + GetInt() Private Shared Function GetInt() As Integer Return 10 End Function ## Private Shared Function Callee(i As Integer) As Integer Return i + i End Function ##End Class") End Function <Fact> Public Function TestInlineInDeconstructor() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Class TestClass Public Sub Finalize() Me.C[||]allee(10) End Sub Private Sub Callee(i As Integer) System.Console.WriteLine(i) End Sub End Class", " Public Class TestClass Public Sub Finalize() System.Console.WriteLine(10) End Sub ## Private Sub Callee(i As Integer) System.Console.WriteLine(i) End Sub ##End Class") End Function <Fact> Public Function TestInlineInProperty() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Class TestClass Readonly Property Caller() As Integer Get Return Call[||]ee(GetInt()) End Get End Property Private Shared Function GetInt() As Integer Return 10 End Function Private Shared Function Callee(i As Integer) As Integer Return i + i End Function End Class", " Public Class TestClass Readonly Property Caller() As Integer Get Dim i As Integer = GetInt() Return i + i End Get End Property Private Shared Function GetInt() As Integer Return 10 End Function ## Private Shared Function Callee(i As Integer) As Integer Return i + i End Function ##End Class") 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.Editor.UnitTests.CodeActions Imports Microsoft.CodeAnalysis.Testing Imports Microsoft.CodeAnalysis.VisualBasic.CodeRefactorings.InlineTemporary Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.InlineMethod <Trait(Traits.Feature, Traits.Features.CodeActionsInlineMethod)> Public Class VisualBasicInlineMethodTests Private Class TestVerifier Inherits VisualBasicCodeRefactoringVerifier(Of VisualBasicInlineMethodRefactoringProvider).Test Private Const Marker As String = "##" Public Shared Async Function TestInRegularAndScriptInDifferentFilesAsync( initialMarkUpForFile1 As String, initialMarkUpForFile2 As String, expectedMarkUpForFile1 As String, expectedMarkUpForFile2 As String, diagnosticResults As List(Of DiagnosticResult), Optional keepInlinedMethod As Boolean = True) As Task Dim test = New TestVerifier() With { .CodeActionIndex = If(keepInlinedMethod, 1, 0), .CodeActionValidationMode = CodeActionValidationMode.None } test.TestState.Sources.Add(("File1", initialMarkUpForFile1)) test.TestState.Sources.Add(("File2", initialMarkUpForFile2)) test.FixedState.Sources.Add(("File1", expectedMarkUpForFile1)) test.FixedState.Sources.Add(("File2", expectedMarkUpForFile2)) If diagnosticResults IsNot Nothing Then test.FixedState.ExpectedDiagnostics.AddRange(diagnosticResults) End If Await test.RunAsync().ConfigureAwait(False) End Function Public Shared Async Function TestInRegularAndScriptAsync( initialMarkUp As String, expectedMarkUp As String, Optional diagnnoticResults As List(Of DiagnosticResult) = Nothing, Optional keepInlinedMethod As Boolean = True) As Task Dim test As New TestVerifier() With {.CodeActionIndex = If(keepInlinedMethod, 1, 0), .CodeActionValidationMode = CodeActionValidationMode.None} test.TestState.Sources.Add(initialMarkUp) test.FixedState.Sources.Add(expectedMarkUp) If diagnnoticResults IsNot Nothing Then test.FixedState.ExpectedDiagnostics.AddRange(diagnnoticResults) End If Await test.RunAsync().ConfigureAwait(False) End Function Public Shared Async Function TestBothKeepAndRemoveInlinedMethodAsync( initialMarkUp As String, expectedMarkUp As String, Optional diagnnoticResultsWhenKeepInlinedMethod As List(Of DiagnosticResult) = Nothing, Optional diagnnoticResultsWhenRemoveInlinedMethod As List(Of DiagnosticResult) = Nothing) As Task Dim firstMarkerIndex = expectedMarkUp.IndexOf(Marker) Dim secondMarkerIndex = expectedMarkUp.LastIndexOf(Marker) If firstMarkerIndex = -1 OrElse secondMarkerIndex = 1 OrElse firstMarkerIndex = secondMarkerIndex Then Assert.True(False, "Can't find proper marks that contains inlined method.") End If Dim firstPartitionBeforeMarkUp = expectedMarkUp.Substring(0, firstMarkerIndex) Dim inlinedMethod = expectedMarkUp.Substring(firstMarkerIndex + 2, secondMarkerIndex - firstMarkerIndex - 2) Dim lastPartitionAfterMarkup = expectedMarkUp.Substring(secondMarkerIndex + 2) Await TestInRegularAndScriptAsync(initialMarkUp, String.Concat(firstPartitionBeforeMarkUp, inlinedMethod, lastPartitionAfterMarkup), diagnnoticResultsWhenKeepInlinedMethod, keepInlinedMethod:=True).ConfigureAwait(False) Await TestInRegularAndScriptAsync(initialMarkUp, String.Concat(firstPartitionBeforeMarkUp, lastPartitionAfterMarkup), diagnnoticResultsWhenRemoveInlinedMethod, keepInlinedMethod:=False).ConfigureAwait(False) End Function Public Shared Async Function TestBothKeepAndRemoveInlinedMethodInDifferentFileAsync( initialMarkUpForCaller As String, initialMarkUpForCallee As String, expectedMarkUpForCaller As String, expectedMarkUpForCallee As String, Optional diagnosticResultsWhenKeepInlinedMethod As List(Of DiagnosticResult) = Nothing, Optional diagnosticResultsWhenRemoveInlinedMethod As List(Of DiagnosticResult) = Nothing) As Task Dim firstMarkerIndex = expectedMarkUpForCallee.IndexOf(Marker) Dim secondMarkerIndex = expectedMarkUpForCallee.LastIndexOf(Marker) If firstMarkerIndex = -1 OrElse secondMarkerIndex = -1 OrElse firstMarkerIndex = secondMarkerIndex Then Assert.True(False, "Can't find proper marks that contains inlined method.") End If Dim firstPartitionBeforeMarkUp = expectedMarkUpForCallee.Substring(0, firstMarkerIndex) Dim inlinedMethod = expectedMarkUpForCallee.Substring(firstMarkerIndex + 2, secondMarkerIndex - firstMarkerIndex - 2) Dim lastPartitionAfterMarkup = expectedMarkUpForCallee.Substring(secondMarkerIndex + 2) Await TestInRegularAndScriptInDifferentFilesAsync( initialMarkUpForCaller, initialMarkUpForCallee, expectedMarkUpForCaller, String.Concat(firstPartitionBeforeMarkUp, inlinedMethod, lastPartitionAfterMarkup), diagnosticResultsWhenKeepInlinedMethod, keepInlinedMethod:=True).ConfigureAwait(False) Await TestInRegularAndScriptInDifferentFilesAsync( initialMarkUpForCaller, initialMarkUpForCallee, expectedMarkUpForCaller, String.Concat(firstPartitionBeforeMarkUp, lastPartitionAfterMarkup), diagnosticResultsWhenRemoveInlinedMethod, keepInlinedMethod:=False).ConfigureAwait(False) End Function End Class <Fact> Public Function TestInlineExpressionStatement() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Class TestClass Public Sub Caller(i As Integer) Me.Ca[||]llee(i) End Sub Private Sub Callee(i As Integer) System.Console.WriteLine(i) End Sub End Class", " Public Class TestClass Public Sub Caller(i As Integer) System.Console.WriteLine(i) End Sub ## Private Sub Callee(i As Integer) System.Console.WriteLine(i) End Sub ##End Class") End Function <Fact> Public Function TestInlineExpressionStatementInDifferentFiles() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodInDifferentFileAsync(" Partial Public Class TestClass Public Sub Caller(i As Integer) Me.Ca[||]llee(i) End Sub End Class", " Partial Public Class TestClass Private Sub Callee(i As Integer) System.Console.WriteLine(i) End Sub End Class", " Partial Public Class TestClass Public Sub Caller(i As Integer) System.Console.WriteLine(i) End Sub End Class", " Partial Public Class TestClass ## Private Sub Callee(i As Integer) System.Console.WriteLine(i) End Sub ##End Class") End Function <Fact> Public Function TestInlineReturnExpression() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Class TestClass Public Sub Caller(i As Integer) Dim x = Me.Ca[||]llee(i) End Sub Private Function Callee(i As Integer) As Integer Return i + 10 End Function End Class", " Public Class TestClass Public Sub Caller(i As Integer) Dim x = i + 10 End Sub ## Private Function Callee(i As Integer) As Integer Return i + 10 End Function ##End Class") End Function <Fact> Public Function TestInlineDefaultValue() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Enum A Value1 Value2 End Enum Public Class TestClass Public Sub Caller() Ca[||]llee() End Sub Private Function Callee(Optional i As Integer = 20, Optional b As Boolean = False, Optional c As A = Nothing) As Integer Return i + If(b, 10, 100) + CType(c, Integer) End Function End Class", " Public Enum A Value1 Value2 End Enum Public Class TestClass Public Sub Caller() Dim temp As Integer = 20 + If(False, 10, 100) + CType(A.Value1, Integer) End Sub ## Private Function Callee(Optional i As Integer = 20, Optional b As Boolean = False, Optional c As A = Nothing) As Integer Return i + If(b, 10, 100) + CType(c, Integer) End Function ##End Class") End Function <Fact> Public Function TestInlineGenerics1() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Class TestClass Public Sub Caller() Ca[||]llee(Of Integer)() End Sub Private Function Callee(Of T)() As String Return GetType(T).ToString() End Function End Class", " Public Class TestClass Public Sub Caller() GetType(Integer).ToString() End Sub ## Private Function Callee(Of T)() As String Return GetType(T).ToString() End Function ##End Class") End Function <Fact> Public Function TestInlineGenerics1InDifferenceFiles() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodInDifferentFileAsync(" Partial Public Class TestClass Public Sub Caller() Ca[||]llee(Of Integer)() End Sub End Class", " Partial Public Class TestClass Private Function Callee(Of T)() As String Return GetType(T).ToString() End Function End Class", " Partial Public Class TestClass Public Sub Caller() GetType(Integer).ToString() End Sub End Class", " Partial Public Class TestClass ## Private Function Callee(Of T)() As String Return GetType(T).ToString() End Function ##End Class") End Function <Fact> Public Function TestInlineGenerics2() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Class TestClass Public Sub Caller() Ca[||]llee(1) End Sub Private Function Callee(Of T)(i As T) As String Return GetType(T).ToString() End Function End Class", " Public Class TestClass Public Sub Caller() GetType(Integer).ToString() End Sub ## Private Function Callee(Of T)(i As T) As String Return GetType(T).ToString() End Function ##End Class") End Function <Fact> Public Function TestInlineWithAddAndMultiple() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Class TestClass Public Sub Caller(i As Integer, j As Integer) Dim x = 1 * Ca[||]llee(i, j) End Sub Private Function Callee(a As Integer, b As Integer) As Integer Return a + b End Function End Class", " Public Class TestClass Public Sub Caller(i As Integer, j As Integer) Dim x = 1 * (i + j) End Sub ## Private Function Callee(a As Integer, b As Integer) As Integer Return a + b End Function ##End Class") End Function <Fact> Public Function TestInlineDefaultValueInDifferentFile() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodInDifferentFileAsync(" Public Enum A Value1 Value2 End Enum Partial Public Class TestClass Public Sub Caller() Ca[||]llee() End Sub End Class", " Partial Public Class TestClass Private Function Callee(Optional i As Integer = 20, Optional b As Boolean = False, Optional c As A = Nothing) As Integer Return i + If(b, 10, 100) + CType(c, Integer) End Function End Class", " Public Enum A Value1 Value2 End Enum Partial Public Class TestClass Public Sub Caller() Dim temp As Integer = 20 + If(False, 10, 100) + CType(A.Value1, Integer) End Sub End Class", " Partial Public Class TestClass ## Private Function Callee(Optional i As Integer = 20, Optional b As Boolean = False, Optional c As A = Nothing) As Integer Return i + If(b, 10, 100) + CType(c, Integer) End Function ##End Class") End Function <Fact> Public Function TestInlineWithLiteralValue() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Enum A Value1 Value2 End Enum Public Class TestClass Public Sub Caller() Ca[||]llee(1, True, A.Value2) End Sub Private Function Callee(Optional i As Integer = 20, Optional b As Boolean = False, Optional c As A = Nothing) As Integer Return i + If(b, 10, 100) + CType(c, Integer) End Function End Class", " Public Enum A Value1 Value2 End Enum Public Class TestClass Public Sub Caller() Dim temp As Integer = 1 + If(True, 10, 100) + CType(A.Value2, Integer) End Sub ## Private Function Callee(Optional i As Integer = 20, Optional b As Boolean = False, Optional c As A = Nothing) As Integer Return i + If(b, 10, 100) + CType(c, Integer) End Function ##End Class") End Function <Fact> Public Function TestInlineWithLiteralValueInDifferentFile() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodInDifferentFileAsync(" Public Enum A Value1 Value2 End Enum Partial Public Class TestClass Public Sub Caller() Ca[||]llee(1, True, A.Value2) End Sub End Class", " Partial Public Class TestClass Private Function Callee(Optional i As Integer = 20, Optional b As Boolean = False, Optional c As A = Nothing) As Integer Return i + If(b, 10, 100) + CType(c, Integer) End Function End Class", " Public Enum A Value1 Value2 End Enum Partial Public Class TestClass Public Sub Caller() Dim temp As Integer = 1 + If(True, 10, 100) + CType(A.Value2, Integer) End Sub End Class", " Partial Public Class TestClass ## Private Function Callee(Optional i As Integer = 20, Optional b As Boolean = False, Optional c As A = Nothing) As Integer Return i + If(b, 10, 100) + CType(c, Integer) End Function ##End Class") End Function <Fact> Public Function TestInlineWithIdentifierReplacement() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Enum A Value1 Value2 End Enum Public Class TestClass Public Sub Caller(c As A) Dim a = 10 Dim b = True Ca[||]llee(a, b, c) End Sub Private Function Callee(Optional i As Integer = 20, Optional b As Boolean = False, Optional c As A = Nothing) As Integer Return i + If(b, 10, 100) + CType(c, Integer) End Function End Class", " Public Enum A Value1 Value2 End Enum Public Class TestClass Public Sub Caller(c As A) Dim a = 10 Dim b = True Dim temp As Integer = a + If(b, 10, 100) + CType(c, Integer) End Sub ## Private Function Callee(Optional i As Integer = 20, Optional b As Boolean = False, Optional c As A = Nothing) As Integer Return i + If(b, 10, 100) + CType(c, Integer) End Function ##End Class") End Function <Fact> Public Function TestInlineWithIdentifierReplacementInDifferentFile() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodInDifferentFileAsync(" Public Enum A Value1 Value2 End Enum Partial Public Class TestClass Public Sub Caller(c As A) Dim a = 10 Dim b = True Ca[||]llee(a, b, c) End Sub End Class", " Partial Public Class TestClass Private Function Callee(Optional i As Integer = 20, Optional b As Boolean = False, Optional c As A = Nothing) As Integer Return i + If(b, 10, 100) + CType(c, Integer) End Function End Class", " Public Enum A Value1 Value2 End Enum Partial Public Class TestClass Public Sub Caller(c As A) Dim a = 10 Dim b = True Dim temp As Integer = a + If(b, 10, 100) + CType(c, Integer) End Sub End Class", " Partial Public Class TestClass ## Private Function Callee(Optional i As Integer = 20, Optional b As Boolean = False, Optional c As A = Nothing) As Integer Return i + If(b, 10, 100) + CType(c, Integer) End Function ##End Class") End Function <Fact> Public Function TestInlineParamArray1() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync( " Public Class TestClass Public Sub Caller() Ca[||]llee(1, 2, 3, 4) End Sub Private Sub Callee(ParamArray args() as Integer) System.Console.WriteLine(args.Length) End Sub End Class", " Public Class TestClass Public Sub Caller() System.Console.WriteLine((New Integer() {1, 2, 3, 4}).Length) End Sub ## Private Sub Callee(ParamArray args() as Integer) System.Console.WriteLine(args.Length) End Sub ##End Class") End Function <Fact> Public Function TestInlineParamArray1InDifferentFile() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodInDifferentFileAsync(" Partial Public Class TestClass Public Sub Caller() Ca[||]llee(1, 2, 3, 4) End Sub End Class", " Partial Public Class TestClass Private Sub Callee(ParamArray args() as Integer) System.Console.WriteLine(args.Length) End Sub End Class", " Partial Public Class TestClass Public Sub Caller() System.Console.WriteLine((New Integer() {1, 2, 3, 4}).Length) End Sub End Class", " Partial Public Class TestClass ## Private Sub Callee(ParamArray args() as Integer) System.Console.WriteLine(args.Length) End Sub ##End Class") End Function <Fact> Public Function TestInlineParamArray2() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync( " Public Class TestClass Public Sub Caller() Ca[||]llee(New Integer() {1, 2, 3, 4}) End Sub Private Sub Callee(ParamArray args() as Integer) System.Console.WriteLine(args.Length) End Sub End Class", " Public Class TestClass Public Sub Caller() System.Console.WriteLine((New Integer() {1, 2, 3, 4}).Length) End Sub ## Private Sub Callee(ParamArray args() as Integer) System.Console.WriteLine(args.Length) End Sub ##End Class") End Function <Fact> Public Function TestInlineParamArray3() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync( " Public Class TestClass Public Sub Caller() Ca[||]llee(1) End Sub Private Sub Callee(ParamArray args() as Integer) System.Console.WriteLine(args.Length) End Sub End Class", " Public Class TestClass Public Sub Caller() System.Console.WriteLine((New Integer() {1}).Length) End Sub ## Private Sub Callee(ParamArray args() as Integer) System.Console.WriteLine(args.Length) End Sub ##End Class") End Function <Fact> Public Function TestInlineParamArray4() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync( " Public Class TestClass Public Sub Caller() Ca[||]llee() End Sub Private Sub Callee(ParamArray args() as Integer) System.Console.WriteLine(args.Length) End Sub End Class", " Public Class TestClass Public Sub Caller() System.Console.WriteLine((New Integer() {}).Length) End Sub ## Private Sub Callee(ParamArray args() as Integer) System.Console.WriteLine(args.Length) End Sub ##End Class") End Function <Fact> Public Function TestInlineParamArray5() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync( " Public Class TestClass Public Sub Caller() Ca[||]llee(1) End Sub Private Sub Callee(ParamArray args() as Integer) System.Console.WriteLine(args.Length) End Sub End Class", " Public Class TestClass Public Sub Caller() System.Console.WriteLine((New Integer() {1}).Length) End Sub ## Private Sub Callee(ParamArray args() as Integer) System.Console.WriteLine(args.Length) End Sub ##End Class") End Function <Fact> Public Function TestInlineSelf() As Task Return TestVerifier.TestInRegularAndScriptAsync(" Public Class TestClass Public Sub Caller(i As Integer) Callee(Callee(Ca[||]llee(i))) End Sub Private Function Callee(i As Integer) As Integer Return i + 10 End Function End Class", " Public Class TestClass Public Sub Caller(i As Integer) Callee(Callee(i + 10)) End Sub Private Function Callee(i As Integer) As Integer Return i + 10 End Function End Class") End Function <Fact> Public Function TestInlineWithLiteralArgument() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Class TestClass Public Sub Caller() Ca[||]llee(5, True) End Sub Private Function Callee(i As Integer, b As Boolean) As Integer Return i + If(b, 10, 100) End Function End Class", " Public Class TestClass Public Sub Caller() Dim temp As Integer = 5 + If(True, 10, 100) End Sub ## Private Function Callee(i As Integer, b As Boolean) As Integer Return i + If(b, 10, 100) End Function ##End Class") End Function <Fact> Public Function TestInlineIdentifierArgument() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Class TestClass Public Sub Caller() Dim i = 2222 Dim x = True Ca[||]llee(i, x) End Sub Private Function Callee(i As Integer, b As Boolean) As Integer Return i + If(b, 10, 100) End Function End Class", " Public Class TestClass Public Sub Caller() Dim i = 2222 Dim x = True Dim temp As Integer = i + If(x, 10, 100) End Sub ## Private Function Callee(i As Integer, b As Boolean) As Integer Return i + If(b, 10, 100) End Function ##End Class") End Function <Fact> Public Function TestInlineInOperator() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Class TestClass Public Shared Operator +(i As TestClass, j As TestClass) Ca[||]llee(10) Return Nothing End Operator Private Shared Sub Callee(i As Integer) System.Console.WriteLine(i) End Sub End Class", " Public Class TestClass Public Shared Operator +(i As TestClass, j As TestClass) System.Console.WriteLine(10) Return Nothing End Operator ## Private Shared Sub Callee(i As Integer) System.Console.WriteLine(i) End Sub ##End Class") End Function <Fact> Public Function TestIdentifierRename() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync( " Public Class TestClass Public Sub Caller(i As Integer, j As Integer) Dim x = Call[||]ee(Cal(i, j), Cal(i, j)) End Sub Private Function Callee(i As Integer, j As Integer) as Integer return i * j End Function Private Function Cal(i As Integer, j As Integer) As Integer Return i + j End Function End Class", " Public Class TestClass Public Sub Caller(i As Integer, j As Integer) Dim x = Cal(i, j) * Cal(i, j) End Sub ## Private Function Callee(i As Integer, j As Integer) as Integer return i * j End Function ## Private Function Cal(i As Integer, j As Integer) As Integer Return i + j End Function End Class") End Function <Fact> Public Function TestInlineLambda1() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync( " Imports System Public Class TestClass Public Sub Caller(i As Integer, j As Integer) Dim x = Call[||]ee(i, j)() End Sub Private Function Callee(i As Integer, j As Integer) as Func(Of Integer) return Function() Return i * j End Function End Function End Class", " Imports System Public Class TestClass Public Sub Caller(i As Integer, j As Integer) Dim x = Function() Return i * j End Function() End Sub ## Private Function Callee(i As Integer, j As Integer) as Func(Of Integer) return Function() Return i * j End Function End Function ##End Class") End Function <Fact> Public Function TestInlineLambda2() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync( " Imports System Public Class TestClass Public Sub Caller(i As Integer, j As Integer) Dim x = Call[||]ee(i, j)() End Sub Private Function Callee(i As Integer, j As Integer) as Func(Of Integer) return Function() i * j End Function End Class", " Imports System Public Class TestClass Public Sub Caller(i As Integer, j As Integer) Dim x = (Function() i * j)() End Sub ## Private Function Callee(i As Integer, j As Integer) as Func(Of Integer) return Function() i * j End Function ##End Class") End Function <Fact> Public Function TestInlineAwaitExpression1() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync( " Imports System.Threading.Tasks Public Class TestClass Public Function Caller() As Task Return Ca[||]llee() End Function Private Async Function Callee() As Task Await Task.Delay(100) End Function End Class", " Imports System.Threading.Tasks Public Class TestClass Public Function Caller() As Task Return Task.Delay(100) End Function ## Private Async Function Callee() As Task Await Task.Delay(100) End Function ##End Class") End Function <Fact> Public Function TestInlineAwaitExpression2() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync( " Imports System.Threading.Tasks Public Class TestClass Public Sub Caller() Dim x = Function(i As Integer) As Task Return Cal[||]lee() End Function End Sub Private Async Function Callee() As Task Await Task.Delay(100) End Function End Class", " Imports System.Threading.Tasks Public Class TestClass Public Sub Caller() Dim x = Function(i As Integer) As Task Return Task.Delay(100) End Function End Sub ## Private Async Function Callee() As Task Await Task.Delay(100) End Function ##End Class") End Function <Fact> Public Function TestInlineAwaitExpression3() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync( " Imports System.Threading.Tasks Public Class TestClass Public Async Function Caller() As Task Await Ca[||]llee() End Function Private Async Function Callee() As Task(Of Integer) Return Await Task.FromResult(1) End Function End Class", " Imports System.Threading.Tasks Public Class TestClass Public Async Function Caller() As Task Await Task.FromResult(1) End Function ## Private Async Function Callee() As Task(Of Integer) Return Await Task.FromResult(1) End Function ##End Class") End Function <Fact> Public Function TestInlineAwaitExpression4() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync( " Imports System.Threading.Tasks Public Class TestClass Public Function Caller() As Task Dim x = Ca[||]llee() End Function Private Async Function Callee() As Task(Of Integer) Return Await Task.FromResult(Await Task.FromResult(100)) End Function End Class", " Imports System.Threading.Tasks Public Class TestClass Public Async Function Caller() As Task Dim x = Task.FromResult(Await Task.FromResult(100)) End Function ## Private Async Function Callee() As Task(Of Integer) Return Await Task.FromResult(Await Task.FromResult(100)) End Function ##End Class") End Function <Fact> Public Function TestThrowStatement() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync( " Imports System Public Class TestClass Public Sub Caller() Ca[||]llee() End Sub Private Function Callee() As Integer Throw New Exception() End Function End Class", " Imports System Public Class TestClass Public Sub Caller() Throw New Exception() End Sub ## Private Function Callee() As Integer Throw New Exception() End Function ##End Class") End Function <Fact> Public Function TestInlineInConstructor() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Class TestClass Public Sub New(i As Integer) Me.Ca[||]llee(i) End Sub Private Sub Callee(i As Integer) System.Console.WriteLine(i) End Sub End Class", " Public Class TestClass Public Sub New(i As Integer) System.Console.WriteLine(i) End Sub ## Private Sub Callee(i As Integer) System.Console.WriteLine(i) End Sub ##End Class") End Function <Fact> Public Function TestInlineReturnExpressionWithoutVariableDeclaration() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Class TestClass Public Sub Caller(i As Integer) Me.Ca[||]llee(i) End Sub Private Function Callee(i As Integer) As Integer Return i + 10 End Function End Class", " Public Class TestClass Public Sub Caller(i As Integer) Dim temp As Integer = i + 10 End Sub ## Private Function Callee(i As Integer) As Integer Return i + 10 End Function ##End Class") End Function <Fact> Public Function TestInlineExpression1() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Class TestClass Public Sub Caller(i As Integer) Me.Ca[||]llee(i * 2) End Sub Private Function Callee(i As Integer) As Integer Return i + i End Function End Class", " Public Class TestClass Public Sub Caller(i As Integer) Dim i1 As Integer = i * 2 Dim temp As Integer = i1 + i1 End Sub ## Private Function Callee(i As Integer) As Integer Return i + i End Function ##End Class") End Function <Fact> Public Function TestInlineInSingleLineLambda() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Class TestClass Public Sub Caller(i As Integer) Dim f = Function() Call[||]ee(GetInt()) End Sub Private Function GetInt() As Integer Return 10 End Function Private Function Callee(i As Integer) As Integer Return i + i End Function End Class", " Public Class TestClass Public Sub Caller(i As Integer) Dim f = Function() GetInt() + GetInt() End Sub Private Function GetInt() As Integer Return 10 End Function ## Private Function Callee(i As Integer) As Integer Return i + i End Function ##End Class") End Function <Fact> Public Function TestInlineInMultiLineLambda() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Class TestClass Public Sub Caller(i As Integer) Dim f = Function() Return Call[||]ee(GetInt()) End Function End Sub Private Function GetInt() As Integer Return 10 End Function Private Function Callee(i As Integer) As Integer Return i + i End Function End Class", " Public Class TestClass Public Sub Caller(i As Integer) Dim f = Function() Dim i1 As Integer = GetInt() Return i1 + i1 End Function End Sub Private Function GetInt() As Integer Return 10 End Function ## Private Function Callee(i As Integer) As Integer Return i + i End Function ##End Class") End Function <Fact> Public Function TestInlineSimpleAssignment() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Class TestClass Public Sub Caller(i As Integer) Dim y As Integer = Call[||]ee(10) End Sub Private Function Callee(i As Integer) As Integer Return i = 100 End Function End Class", " Public Class TestClass Public Sub Caller(i As Integer) Dim y As Integer = 10 = 100 End Sub ## Private Function Callee(i As Integer) As Integer Return i = 100 End Function ##End Class") End Function <Fact> Public Function TestInlineInDoWhileStatement() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Class TestClass Public Sub Caller(i As Boolean) Do Loop While Ca[||]llee(GetFlag()) End Sub Private Function GetFlag() As Boolean Return True End Function Private Function Callee(a As Boolean) As Boolean Return a OrElse a End Function End Class", " Public Class TestClass Public Sub Caller(i As Boolean) Dim a As Boolean = GetFlag() Do Loop While a OrElse a End Sub Private Function GetFlag() As Boolean Return True End Function ## Private Function Callee(a As Boolean) As Boolean Return a OrElse a End Function ##End Class") End Function <Fact> Public Function TestInlineInWhileStatement() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Class TestClass Public Sub Caller(i As Boolean) While Ca[||]llee(GetFlag()) End While End Sub Private Function GetFlag() As Boolean Return True End Function Private Function Callee(a As Boolean) As Boolean Return a OrElse a End Function End Class", " Public Class TestClass Public Sub Caller(i As Boolean) Dim a As Boolean = GetFlag() While a OrElse a End While End Sub Private Function GetFlag() As Boolean Return True End Function ## Private Function Callee(a As Boolean) As Boolean Return a OrElse a End Function ##End Class") End Function <Fact> Public Function TestInlineInIfStatement() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Class TestClass Public Sub Caller(i As Boolean) If C[||]allee(GetFlag()) OrElse True Then End If End Sub Private Function GetFlag() As Boolean Return True End Function Private Function Callee(a As Boolean) As Boolean Return a OrElse a End Function End Class", " Public Class TestClass Public Sub Caller(i As Boolean) Dim a As Boolean = GetFlag() If a OrElse a OrElse True Then End If End Sub Private Function GetFlag() As Boolean Return True End Function ## Private Function Callee(a As Boolean) As Boolean Return a OrElse a End Function ##End Class") End Function <Fact> Public Function TestInlineWithinLockStatement() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Class TestClass Public Sub Caller() SyncLock Ca[||]llee(GetFlag()) End SyncLock End Sub Private Function GetFlag() As Integer Return 10 End Function Private Function Callee(a As Integer) As String Return (a + a).ToString() End Function End Class", " Public Class TestClass Public Sub Caller() Dim a As Integer = GetFlag() SyncLock (a + a).ToString() End SyncLock End Sub Private Function GetFlag() As Integer Return 10 End Function ## Private Function Callee(a As Integer) As String Return (a + a).ToString() End Function ##End Class") End Function <Fact> Public Function TestInlineConditionalExpression() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Class TestClass Public Sub Caller(i As Integer) Dim y = Call[||]ee(true) End Sub Private Function Callee(a As Boolean) As Integer Return If (a, 10, 100) End Function End Class", " Public Class TestClass Public Sub Caller(i As Integer) Dim y = If (true, 10, 100) End Sub ## Private Function Callee(a As Boolean) As Integer Return If (a, 10, 100) End Function ##End Class") End Function <Fact> Public Function TestInlineInInvocation() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Class TestClass Public Sub Caller(i As Integer) Callee(Ge[||]tInt()) End Sub Private Function Callee(i As Integer) As Integer Return i + i End Function Private Function GetInt() As Integer Return 10 End Function End Class", " Public Class TestClass Public Sub Caller(i As Integer) Callee(10) End Sub Private Function Callee(i As Integer) As Integer Return i + i End Function ## Private Function GetInt() As Integer Return 10 End Function ##End Class") End Function <Fact> Public Function TestExtensionMethod() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync( " Imports System.Runtime.CompilerServices Module TestModule Sub Main() Dim i = 1 Dim i2 = i.Ca[||]llee() End Sub <Extension()> Private Function Callee(i As Integer) As Integer Return i + 1 End Function End Module", " Imports System.Runtime.CompilerServices Module TestModule Sub Main() Dim i = 1 Dim i2 = i + 1 End Sub ## <Extension()> Private Function Callee(i As Integer) As Integer Return i + 1 End Function ##End Module") End Function <Fact> Public Function TestInlineInField() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Class TestClass Private TestField As Integer = Cal[||]lee(GetInt()) Private Shared Function GetInt() As Integer Return 10 End Function Private Shared Function Callee(i As Integer) As Integer Return i + i End Function End Class", " Public Class TestClass Private TestField As Integer = GetInt() + GetInt() Private Shared Function GetInt() As Integer Return 10 End Function ## Private Shared Function Callee(i As Integer) As Integer Return i + i End Function ##End Class") End Function <Fact> Public Function TestInlineInDeconstructor() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Class TestClass Public Sub Finalize() Me.C[||]allee(10) End Sub Private Sub Callee(i As Integer) System.Console.WriteLine(i) End Sub End Class", " Public Class TestClass Public Sub Finalize() System.Console.WriteLine(10) End Sub ## Private Sub Callee(i As Integer) System.Console.WriteLine(i) End Sub ##End Class") End Function <Fact> Public Function TestInlineInProperty() As Task Return TestVerifier.TestBothKeepAndRemoveInlinedMethodAsync(" Public Class TestClass Readonly Property Caller() As Integer Get Return Call[||]ee(GetInt()) End Get End Property Private Shared Function GetInt() As Integer Return 10 End Function Private Shared Function Callee(i As Integer) As Integer Return i + i End Function End Class", " Public Class TestClass Readonly Property Caller() As Integer Get Dim i As Integer = GetInt() Return i + i End Get End Property Private Shared Function GetInt() As Integer Return 10 End Function ## Private Shared Function Callee(i As Integer) As Integer Return i + i End Function ##End Class") End Function End Class End Namespace
-1
dotnet/roslyn
55,409
Use FixedSize API
tmat
2021-08-04T19:30:40Z
2021-08-04T21:53:46Z
e0112742bff208dd0546de45e36f7b52058a45a3
c90bf0ec986010051662c8e1fbc872c2fd86bc4e
Use FixedSize API.
./src/Features/Core/Portable/EmbeddedLanguages/RegularExpressions/LanguageServices/RegexSyntaxClassifier.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Classification.Classifiers; using Microsoft.CodeAnalysis.EmbeddedLanguages.Common; using Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions.LanguageServices { using static EmbeddedSyntaxHelpers; using RegexToken = EmbeddedSyntaxToken<RegexKind>; using RegexTrivia = EmbeddedSyntaxTrivia<RegexKind>; /// <summary> /// Classifier impl for embedded regex strings. /// </summary> internal sealed class RegexSyntaxClassifier : AbstractSyntaxClassifier { private static readonly ObjectPool<Visitor> s_visitorPool = SharedPools.Default<Visitor>(); private readonly EmbeddedLanguageInfo _info; public override ImmutableArray<int> SyntaxTokenKinds { get; } public RegexSyntaxClassifier(EmbeddedLanguageInfo info) { _info = info; SyntaxTokenKinds = ImmutableArray.Create(info.StringLiteralTokenKind); } public override void AddClassifications( Workspace workspace, SyntaxToken token, SemanticModel semanticModel, ArrayBuilder<ClassifiedSpan> result, CancellationToken cancellationToken) { if (_info.StringLiteralTokenKind != token.RawKind) { return; } if (!workspace.Options.GetOption(RegularExpressionsOptions.ColorizeRegexPatterns, semanticModel.Language)) { return; } // Do some quick syntactic checks before doing any complex work. if (!RegexPatternDetector.IsPossiblyPatternToken(token, _info.SyntaxFacts)) { return; } var detector = RegexPatternDetector.TryGetOrCreate(semanticModel.Compilation, _info); var tree = detector?.TryParseRegexPattern(token, semanticModel, cancellationToken); if (tree == null) { return; } var visitor = s_visitorPool.Allocate(); try { visitor.Result = result; AddClassifications(tree.Root, visitor, result); } finally { visitor.Result = null; s_visitorPool.Free(visitor); } } private static void AddClassifications(RegexNode node, Visitor visitor, ArrayBuilder<ClassifiedSpan> result) { node.Accept(visitor); foreach (var child in node) { if (child.IsNode) { AddClassifications(child.Node, visitor, result); } else { AddTriviaClassifications(child.Token, result); } } } private static void AddTriviaClassifications(RegexToken token, ArrayBuilder<ClassifiedSpan> result) { foreach (var trivia in token.LeadingTrivia) { AddTriviaClassifications(trivia, result); } } private static void AddTriviaClassifications(RegexTrivia trivia, ArrayBuilder<ClassifiedSpan> result) { if (trivia.Kind == RegexKind.CommentTrivia && trivia.VirtualChars.Length > 0) { result.Add(new ClassifiedSpan( ClassificationTypeNames.RegexComment, GetSpan(trivia.VirtualChars))); } } private class Visitor : IRegexNodeVisitor { public ArrayBuilder<ClassifiedSpan> Result; private void AddClassification(RegexToken token, string typeName) { if (!token.IsMissing) { Result.Add(new ClassifiedSpan(typeName, token.GetSpan())); } } private void ClassifyWholeNode(RegexNode node, string typeName) { foreach (var child in node) { if (child.IsNode) { ClassifyWholeNode(child.Node, typeName); } else { AddClassification(child.Token, typeName); } } } public void Visit(RegexCompilationUnit node) { // Nothing to highlight. } public void Visit(RegexSequenceNode node) { // Nothing to highlight. } #region Character classes public void Visit(RegexWildcardNode node) => AddClassification(node.DotToken, ClassificationTypeNames.RegexCharacterClass); public void Visit(RegexCharacterClassNode node) { AddClassification(node.OpenBracketToken, ClassificationTypeNames.RegexCharacterClass); AddClassification(node.CloseBracketToken, ClassificationTypeNames.RegexCharacterClass); } public void Visit(RegexNegatedCharacterClassNode node) { AddClassification(node.OpenBracketToken, ClassificationTypeNames.RegexCharacterClass); AddClassification(node.CaretToken, ClassificationTypeNames.RegexCharacterClass); AddClassification(node.CloseBracketToken, ClassificationTypeNames.RegexCharacterClass); } public void Visit(RegexCharacterClassRangeNode node) => AddClassification(node.MinusToken, ClassificationTypeNames.RegexCharacterClass); public void Visit(RegexCharacterClassSubtractionNode node) => AddClassification(node.MinusToken, ClassificationTypeNames.RegexCharacterClass); public void Visit(RegexCharacterClassEscapeNode node) => ClassifyWholeNode(node, ClassificationTypeNames.RegexCharacterClass); public void Visit(RegexCategoryEscapeNode node) => ClassifyWholeNode(node, ClassificationTypeNames.RegexCharacterClass); #endregion #region Quantifiers public void Visit(RegexZeroOrMoreQuantifierNode node) => AddClassification(node.AsteriskToken, ClassificationTypeNames.RegexQuantifier); public void Visit(RegexOneOrMoreQuantifierNode node) => AddClassification(node.PlusToken, ClassificationTypeNames.RegexQuantifier); public void Visit(RegexZeroOrOneQuantifierNode node) => AddClassification(node.QuestionToken, ClassificationTypeNames.RegexQuantifier); public void Visit(RegexLazyQuantifierNode node) => AddClassification(node.QuestionToken, ClassificationTypeNames.RegexQuantifier); public void Visit(RegexExactNumericQuantifierNode node) { AddClassification(node.OpenBraceToken, ClassificationTypeNames.RegexQuantifier); AddClassification(node.FirstNumberToken, ClassificationTypeNames.RegexQuantifier); AddClassification(node.CloseBraceToken, ClassificationTypeNames.RegexQuantifier); } public void Visit(RegexOpenNumericRangeQuantifierNode node) { AddClassification(node.OpenBraceToken, ClassificationTypeNames.RegexQuantifier); AddClassification(node.FirstNumberToken, ClassificationTypeNames.RegexQuantifier); AddClassification(node.CommaToken, ClassificationTypeNames.RegexQuantifier); AddClassification(node.CloseBraceToken, ClassificationTypeNames.RegexQuantifier); } public void Visit(RegexClosedNumericRangeQuantifierNode node) { AddClassification(node.OpenBraceToken, ClassificationTypeNames.RegexQuantifier); AddClassification(node.FirstNumberToken, ClassificationTypeNames.RegexQuantifier); AddClassification(node.CommaToken, ClassificationTypeNames.RegexQuantifier); AddClassification(node.SecondNumberToken, ClassificationTypeNames.RegexQuantifier); AddClassification(node.CloseBraceToken, ClassificationTypeNames.RegexQuantifier); } #endregion #region Groupings public void Visit(RegexSimpleGroupingNode node) => ClassifyGrouping(node); public void Visit(RegexSimpleOptionsGroupingNode node) => ClassifyGrouping(node); public void Visit(RegexNestedOptionsGroupingNode node) => ClassifyGrouping(node); public void Visit(RegexNonCapturingGroupingNode node) => ClassifyGrouping(node); public void Visit(RegexPositiveLookaheadGroupingNode node) => ClassifyGrouping(node); public void Visit(RegexNegativeLookaheadGroupingNode node) => ClassifyGrouping(node); public void Visit(RegexPositiveLookbehindGroupingNode node) => ClassifyGrouping(node); public void Visit(RegexNegativeLookbehindGroupingNode node) => ClassifyGrouping(node); public void Visit(RegexAtomicGroupingNode node) => ClassifyGrouping(node); public void Visit(RegexCaptureGroupingNode node) => ClassifyGrouping(node); public void Visit(RegexBalancingGroupingNode node) => ClassifyGrouping(node); public void Visit(RegexConditionalCaptureGroupingNode node) => ClassifyGrouping(node); public void Visit(RegexConditionalExpressionGroupingNode node) => ClassifyGrouping(node); // Captures and backreferences refer to groups. So we classify them the same way as groups. public void Visit(RegexCaptureEscapeNode node) => ClassifyWholeNode(node, ClassificationTypeNames.RegexGrouping); public void Visit(RegexKCaptureEscapeNode node) => ClassifyWholeNode(node, ClassificationTypeNames.RegexGrouping); public void Visit(RegexBackreferenceEscapeNode node) => ClassifyWholeNode(node, ClassificationTypeNames.RegexGrouping); private void ClassifyGrouping(RegexGroupingNode node) { foreach (var child in node) { if (!child.IsNode) { AddClassification(child.Token, ClassificationTypeNames.RegexGrouping); } } } #endregion #region Other Escapes public void Visit(RegexControlEscapeNode node) => ClassifyOtherEscape(node); public void Visit(RegexHexEscapeNode node) => ClassifyOtherEscape(node); public void Visit(RegexUnicodeEscapeNode node) => ClassifyOtherEscape(node); public void Visit(RegexOctalEscapeNode node) => ClassifyOtherEscape(node); public void ClassifyOtherEscape(RegexNode node) => ClassifyWholeNode(node, ClassificationTypeNames.RegexOtherEscape); #endregion #region Anchors public void Visit(RegexAnchorNode node) => AddClassification(node.AnchorToken, ClassificationTypeNames.RegexAnchor); public void Visit(RegexAnchorEscapeNode node) => ClassifyWholeNode(node, ClassificationTypeNames.RegexAnchor); #endregion public void Visit(RegexTextNode node) => AddClassification(node.TextToken, ClassificationTypeNames.RegexText); public void Visit(RegexPosixPropertyNode node) { // The .NET parser just interprets the [ of the node, and skips the rest. So // classify the end part as a comment. Result.Add(new ClassifiedSpan(node.TextToken.VirtualChars[0].Span, ClassificationTypeNames.RegexText)); Result.Add(new ClassifiedSpan( GetSpan(node.TextToken.VirtualChars[1], node.TextToken.VirtualChars.Last()), ClassificationTypeNames.RegexComment)); } public void Visit(RegexAlternationNode node) => AddClassification(node.BarToken, ClassificationTypeNames.RegexAlternation); public void Visit(RegexSimpleEscapeNode node) => ClassifyWholeNode(node, node.IsSelfEscape() ? ClassificationTypeNames.RegexSelfEscapedCharacter : ClassificationTypeNames.RegexOtherEscape); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Classification.Classifiers; using Microsoft.CodeAnalysis.EmbeddedLanguages.Common; using Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions.LanguageServices { using static EmbeddedSyntaxHelpers; using RegexToken = EmbeddedSyntaxToken<RegexKind>; using RegexTrivia = EmbeddedSyntaxTrivia<RegexKind>; /// <summary> /// Classifier impl for embedded regex strings. /// </summary> internal sealed class RegexSyntaxClassifier : AbstractSyntaxClassifier { private static readonly ObjectPool<Visitor> s_visitorPool = SharedPools.Default<Visitor>(); private readonly EmbeddedLanguageInfo _info; public override ImmutableArray<int> SyntaxTokenKinds { get; } public RegexSyntaxClassifier(EmbeddedLanguageInfo info) { _info = info; SyntaxTokenKinds = ImmutableArray.Create(info.StringLiteralTokenKind); } public override void AddClassifications( Workspace workspace, SyntaxToken token, SemanticModel semanticModel, ArrayBuilder<ClassifiedSpan> result, CancellationToken cancellationToken) { if (_info.StringLiteralTokenKind != token.RawKind) { return; } if (!workspace.Options.GetOption(RegularExpressionsOptions.ColorizeRegexPatterns, semanticModel.Language)) { return; } // Do some quick syntactic checks before doing any complex work. if (!RegexPatternDetector.IsPossiblyPatternToken(token, _info.SyntaxFacts)) { return; } var detector = RegexPatternDetector.TryGetOrCreate(semanticModel.Compilation, _info); var tree = detector?.TryParseRegexPattern(token, semanticModel, cancellationToken); if (tree == null) { return; } var visitor = s_visitorPool.Allocate(); try { visitor.Result = result; AddClassifications(tree.Root, visitor, result); } finally { visitor.Result = null; s_visitorPool.Free(visitor); } } private static void AddClassifications(RegexNode node, Visitor visitor, ArrayBuilder<ClassifiedSpan> result) { node.Accept(visitor); foreach (var child in node) { if (child.IsNode) { AddClassifications(child.Node, visitor, result); } else { AddTriviaClassifications(child.Token, result); } } } private static void AddTriviaClassifications(RegexToken token, ArrayBuilder<ClassifiedSpan> result) { foreach (var trivia in token.LeadingTrivia) { AddTriviaClassifications(trivia, result); } } private static void AddTriviaClassifications(RegexTrivia trivia, ArrayBuilder<ClassifiedSpan> result) { if (trivia.Kind == RegexKind.CommentTrivia && trivia.VirtualChars.Length > 0) { result.Add(new ClassifiedSpan( ClassificationTypeNames.RegexComment, GetSpan(trivia.VirtualChars))); } } private class Visitor : IRegexNodeVisitor { public ArrayBuilder<ClassifiedSpan> Result; private void AddClassification(RegexToken token, string typeName) { if (!token.IsMissing) { Result.Add(new ClassifiedSpan(typeName, token.GetSpan())); } } private void ClassifyWholeNode(RegexNode node, string typeName) { foreach (var child in node) { if (child.IsNode) { ClassifyWholeNode(child.Node, typeName); } else { AddClassification(child.Token, typeName); } } } public void Visit(RegexCompilationUnit node) { // Nothing to highlight. } public void Visit(RegexSequenceNode node) { // Nothing to highlight. } #region Character classes public void Visit(RegexWildcardNode node) => AddClassification(node.DotToken, ClassificationTypeNames.RegexCharacterClass); public void Visit(RegexCharacterClassNode node) { AddClassification(node.OpenBracketToken, ClassificationTypeNames.RegexCharacterClass); AddClassification(node.CloseBracketToken, ClassificationTypeNames.RegexCharacterClass); } public void Visit(RegexNegatedCharacterClassNode node) { AddClassification(node.OpenBracketToken, ClassificationTypeNames.RegexCharacterClass); AddClassification(node.CaretToken, ClassificationTypeNames.RegexCharacterClass); AddClassification(node.CloseBracketToken, ClassificationTypeNames.RegexCharacterClass); } public void Visit(RegexCharacterClassRangeNode node) => AddClassification(node.MinusToken, ClassificationTypeNames.RegexCharacterClass); public void Visit(RegexCharacterClassSubtractionNode node) => AddClassification(node.MinusToken, ClassificationTypeNames.RegexCharacterClass); public void Visit(RegexCharacterClassEscapeNode node) => ClassifyWholeNode(node, ClassificationTypeNames.RegexCharacterClass); public void Visit(RegexCategoryEscapeNode node) => ClassifyWholeNode(node, ClassificationTypeNames.RegexCharacterClass); #endregion #region Quantifiers public void Visit(RegexZeroOrMoreQuantifierNode node) => AddClassification(node.AsteriskToken, ClassificationTypeNames.RegexQuantifier); public void Visit(RegexOneOrMoreQuantifierNode node) => AddClassification(node.PlusToken, ClassificationTypeNames.RegexQuantifier); public void Visit(RegexZeroOrOneQuantifierNode node) => AddClassification(node.QuestionToken, ClassificationTypeNames.RegexQuantifier); public void Visit(RegexLazyQuantifierNode node) => AddClassification(node.QuestionToken, ClassificationTypeNames.RegexQuantifier); public void Visit(RegexExactNumericQuantifierNode node) { AddClassification(node.OpenBraceToken, ClassificationTypeNames.RegexQuantifier); AddClassification(node.FirstNumberToken, ClassificationTypeNames.RegexQuantifier); AddClassification(node.CloseBraceToken, ClassificationTypeNames.RegexQuantifier); } public void Visit(RegexOpenNumericRangeQuantifierNode node) { AddClassification(node.OpenBraceToken, ClassificationTypeNames.RegexQuantifier); AddClassification(node.FirstNumberToken, ClassificationTypeNames.RegexQuantifier); AddClassification(node.CommaToken, ClassificationTypeNames.RegexQuantifier); AddClassification(node.CloseBraceToken, ClassificationTypeNames.RegexQuantifier); } public void Visit(RegexClosedNumericRangeQuantifierNode node) { AddClassification(node.OpenBraceToken, ClassificationTypeNames.RegexQuantifier); AddClassification(node.FirstNumberToken, ClassificationTypeNames.RegexQuantifier); AddClassification(node.CommaToken, ClassificationTypeNames.RegexQuantifier); AddClassification(node.SecondNumberToken, ClassificationTypeNames.RegexQuantifier); AddClassification(node.CloseBraceToken, ClassificationTypeNames.RegexQuantifier); } #endregion #region Groupings public void Visit(RegexSimpleGroupingNode node) => ClassifyGrouping(node); public void Visit(RegexSimpleOptionsGroupingNode node) => ClassifyGrouping(node); public void Visit(RegexNestedOptionsGroupingNode node) => ClassifyGrouping(node); public void Visit(RegexNonCapturingGroupingNode node) => ClassifyGrouping(node); public void Visit(RegexPositiveLookaheadGroupingNode node) => ClassifyGrouping(node); public void Visit(RegexNegativeLookaheadGroupingNode node) => ClassifyGrouping(node); public void Visit(RegexPositiveLookbehindGroupingNode node) => ClassifyGrouping(node); public void Visit(RegexNegativeLookbehindGroupingNode node) => ClassifyGrouping(node); public void Visit(RegexAtomicGroupingNode node) => ClassifyGrouping(node); public void Visit(RegexCaptureGroupingNode node) => ClassifyGrouping(node); public void Visit(RegexBalancingGroupingNode node) => ClassifyGrouping(node); public void Visit(RegexConditionalCaptureGroupingNode node) => ClassifyGrouping(node); public void Visit(RegexConditionalExpressionGroupingNode node) => ClassifyGrouping(node); // Captures and backreferences refer to groups. So we classify them the same way as groups. public void Visit(RegexCaptureEscapeNode node) => ClassifyWholeNode(node, ClassificationTypeNames.RegexGrouping); public void Visit(RegexKCaptureEscapeNode node) => ClassifyWholeNode(node, ClassificationTypeNames.RegexGrouping); public void Visit(RegexBackreferenceEscapeNode node) => ClassifyWholeNode(node, ClassificationTypeNames.RegexGrouping); private void ClassifyGrouping(RegexGroupingNode node) { foreach (var child in node) { if (!child.IsNode) { AddClassification(child.Token, ClassificationTypeNames.RegexGrouping); } } } #endregion #region Other Escapes public void Visit(RegexControlEscapeNode node) => ClassifyOtherEscape(node); public void Visit(RegexHexEscapeNode node) => ClassifyOtherEscape(node); public void Visit(RegexUnicodeEscapeNode node) => ClassifyOtherEscape(node); public void Visit(RegexOctalEscapeNode node) => ClassifyOtherEscape(node); public void ClassifyOtherEscape(RegexNode node) => ClassifyWholeNode(node, ClassificationTypeNames.RegexOtherEscape); #endregion #region Anchors public void Visit(RegexAnchorNode node) => AddClassification(node.AnchorToken, ClassificationTypeNames.RegexAnchor); public void Visit(RegexAnchorEscapeNode node) => ClassifyWholeNode(node, ClassificationTypeNames.RegexAnchor); #endregion public void Visit(RegexTextNode node) => AddClassification(node.TextToken, ClassificationTypeNames.RegexText); public void Visit(RegexPosixPropertyNode node) { // The .NET parser just interprets the [ of the node, and skips the rest. So // classify the end part as a comment. Result.Add(new ClassifiedSpan(node.TextToken.VirtualChars[0].Span, ClassificationTypeNames.RegexText)); Result.Add(new ClassifiedSpan( GetSpan(node.TextToken.VirtualChars[1], node.TextToken.VirtualChars.Last()), ClassificationTypeNames.RegexComment)); } public void Visit(RegexAlternationNode node) => AddClassification(node.BarToken, ClassificationTypeNames.RegexAlternation); public void Visit(RegexSimpleEscapeNode node) => ClassifyWholeNode(node, node.IsSelfEscape() ? ClassificationTypeNames.RegexSelfEscapedCharacter : ClassificationTypeNames.RegexOtherEscape); } } }
-1
dotnet/roslyn
55,409
Use FixedSize API
tmat
2021-08-04T19:30:40Z
2021-08-04T21:53:46Z
e0112742bff208dd0546de45e36f7b52058a45a3
c90bf0ec986010051662c8e1fbc872c2fd86bc4e
Use FixedSize API.
./src/Compilers/Test/Core/CultureContext.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Globalization; using System.Threading; namespace Roslyn.Test.Utilities { public class CultureContext : IDisposable { private readonly CultureInfo _threadCulture; public CultureContext(CultureInfo cultureInfo) { _threadCulture = CultureInfo.CurrentCulture; CultureInfo.CurrentCulture = cultureInfo; } public void Dispose() { CultureInfo.CurrentCulture = _threadCulture; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Globalization; using System.Threading; namespace Roslyn.Test.Utilities { public class CultureContext : IDisposable { private readonly CultureInfo _threadCulture; public CultureContext(CultureInfo cultureInfo) { _threadCulture = CultureInfo.CurrentCulture; CultureInfo.CurrentCulture = cultureInfo; } public void Dispose() { CultureInfo.CurrentCulture = _threadCulture; } } }
-1
dotnet/roslyn
55,409
Use FixedSize API
tmat
2021-08-04T19:30:40Z
2021-08-04T21:53:46Z
e0112742bff208dd0546de45e36f7b52058a45a3
c90bf0ec986010051662c8e1fbc872c2fd86bc4e
Use FixedSize API.
./src/Compilers/CSharp/Portable/Errors/DiagnosticBagExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.CSharp { internal static class DiagnosticBagExtensions { /// <summary> /// Add a diagnostic to the bag. /// </summary> /// <param name="diagnostics"></param> /// <param name="code"></param> /// <param name="location"></param> /// <returns></returns> internal static CSDiagnosticInfo Add(this DiagnosticBag diagnostics, ErrorCode code, Location location) { var info = new CSDiagnosticInfo(code); var diag = new CSDiagnostic(info, location); diagnostics.Add(diag); return info; } /// <summary> /// Add a diagnostic to the bag. /// </summary> /// <param name="diagnostics"></param> /// <param name="code"></param> /// <param name="location"></param> /// <param name="args"></param> /// <returns></returns> internal static CSDiagnosticInfo Add(this DiagnosticBag diagnostics, ErrorCode code, Location location, params object[] args) { var info = new CSDiagnosticInfo(code, args); var diag = new CSDiagnostic(info, location); diagnostics.Add(diag); return info; } internal static CSDiagnosticInfo Add(this DiagnosticBag diagnostics, ErrorCode code, Location location, ImmutableArray<Symbol> symbols, params object[] args) { var info = new CSDiagnosticInfo(code, args, symbols, ImmutableArray<Location>.Empty); var diag = new CSDiagnostic(info, location); diagnostics.Add(diag); return info; } internal static void Add(this DiagnosticBag diagnostics, DiagnosticInfo info, Location location) { var diag = new CSDiagnostic(info, location); diagnostics.Add(diag); } /// <summary> /// Adds diagnostics from useSiteDiagnostics into diagnostics and returns True if there were any errors. /// </summary> internal static bool Add( this DiagnosticBag diagnostics, SyntaxNode node, HashSet<DiagnosticInfo> useSiteDiagnostics) { return !useSiteDiagnostics.IsNullOrEmpty() && diagnostics.Add(node.Location, useSiteDiagnostics); } /// <summary> /// Adds diagnostics from useSiteDiagnostics into diagnostics and returns True if there were any errors. /// </summary> internal static bool Add( this DiagnosticBag diagnostics, SyntaxToken token, HashSet<DiagnosticInfo> useSiteDiagnostics) { return !useSiteDiagnostics.IsNullOrEmpty() && diagnostics.Add(token.GetLocation(), useSiteDiagnostics); } internal static bool Add( this DiagnosticBag diagnostics, Location location, IReadOnlyCollection<DiagnosticInfo> useSiteDiagnostics) { if (useSiteDiagnostics.IsNullOrEmpty()) { return false; } bool haveErrors = false; foreach (var info in useSiteDiagnostics) { if (info.Severity == DiagnosticSeverity.Error) { haveErrors = true; } diagnostics.Add(new CSDiagnostic(info, location)); } return haveErrors; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.CSharp { internal static class DiagnosticBagExtensions { /// <summary> /// Add a diagnostic to the bag. /// </summary> /// <param name="diagnostics"></param> /// <param name="code"></param> /// <param name="location"></param> /// <returns></returns> internal static CSDiagnosticInfo Add(this DiagnosticBag diagnostics, ErrorCode code, Location location) { var info = new CSDiagnosticInfo(code); var diag = new CSDiagnostic(info, location); diagnostics.Add(diag); return info; } /// <summary> /// Add a diagnostic to the bag. /// </summary> /// <param name="diagnostics"></param> /// <param name="code"></param> /// <param name="location"></param> /// <param name="args"></param> /// <returns></returns> internal static CSDiagnosticInfo Add(this DiagnosticBag diagnostics, ErrorCode code, Location location, params object[] args) { var info = new CSDiagnosticInfo(code, args); var diag = new CSDiagnostic(info, location); diagnostics.Add(diag); return info; } internal static CSDiagnosticInfo Add(this DiagnosticBag diagnostics, ErrorCode code, Location location, ImmutableArray<Symbol> symbols, params object[] args) { var info = new CSDiagnosticInfo(code, args, symbols, ImmutableArray<Location>.Empty); var diag = new CSDiagnostic(info, location); diagnostics.Add(diag); return info; } internal static void Add(this DiagnosticBag diagnostics, DiagnosticInfo info, Location location) { var diag = new CSDiagnostic(info, location); diagnostics.Add(diag); } /// <summary> /// Adds diagnostics from useSiteDiagnostics into diagnostics and returns True if there were any errors. /// </summary> internal static bool Add( this DiagnosticBag diagnostics, SyntaxNode node, HashSet<DiagnosticInfo> useSiteDiagnostics) { return !useSiteDiagnostics.IsNullOrEmpty() && diagnostics.Add(node.Location, useSiteDiagnostics); } /// <summary> /// Adds diagnostics from useSiteDiagnostics into diagnostics and returns True if there were any errors. /// </summary> internal static bool Add( this DiagnosticBag diagnostics, SyntaxToken token, HashSet<DiagnosticInfo> useSiteDiagnostics) { return !useSiteDiagnostics.IsNullOrEmpty() && diagnostics.Add(token.GetLocation(), useSiteDiagnostics); } internal static bool Add( this DiagnosticBag diagnostics, Location location, IReadOnlyCollection<DiagnosticInfo> useSiteDiagnostics) { if (useSiteDiagnostics.IsNullOrEmpty()) { return false; } bool haveErrors = false; foreach (var info in useSiteDiagnostics) { if (info.Severity == DiagnosticSeverity.Error) { haveErrors = true; } diagnostics.Add(new CSDiagnostic(info, location)); } return haveErrors; } } }
-1
dotnet/roslyn
55,409
Use FixedSize API
tmat
2021-08-04T19:30:40Z
2021-08-04T21:53:46Z
e0112742bff208dd0546de45e36f7b52058a45a3
c90bf0ec986010051662c8e1fbc872c2fd86bc4e
Use FixedSize API.
./src/Compilers/Test/Resources/Core/SymbolsTests/V2/MTTestLib3.Dll
MZ@ !L!This program cannot be run in DOS mode. $PELUśL! / @@ @/K@`  H.text  `.rsrc@@@.reloc `@B/H@"` ( *( *s s s s *0~o +*0~o +*0~o +*0~o +*0( ( +*0 ( +*0( +*0 ( +*0 - (+ ++ +*0 *( *0, { o -(+ { o  +*J( s } *( *0  +*0  +*0 +*BSJB v4.0.30319ld#~#Strings #US #GUID h#BlobW %3&    E Eu9& xQ < U)7:7 E7 O ] x 1 11-1S:1xG!TP X `   !( J5 hB Fc!Fh4!lP!Fqh!x!!! !!"|"," Qai$,4<$ , 4 < qy fch)*sqFDTLpLzL9)H.>.G@+@CCI cciY+{s4++$++ + @@+``++++++ koz*/4OTEY^^  uu j -- <Module>mscorlibMicrosoft.VisualBasicMyApplicationMyMyComputerMyProjectMyWebServicesThreadSafeObjectProvider`1Class5Microsoft.VisualBasic.ApplicationServicesApplicationBase.ctorMicrosoft.VisualBasic.DevicesComputerSystemObject.cctorget_Computerm_ComputerObjectProviderget_Applicationm_AppObjectProviderUserget_Userm_UserObjectProviderget_WebServicesm_MyWebServicesObjectProviderApplicationWebServicesEqualsoGetHashCodeTypeGetTypeToStringCreate__Instance__TinstanceDispose__Instance__get_GetInstanceMicrosoft.VisualBasic.MyServices.InternalContextValue`1m_ContextGetInstanceMTTestLib1Class1Foo1Class2Foo2MTTestLib2Class4Foo3Bar1Bar2Bar3System.ComponentModelEditorBrowsableAttributeEditorBrowsableStateSystem.CodeDom.CompilerGeneratedCodeAttributeSystem.DiagnosticsDebuggerHiddenAttributeMicrosoft.VisualBasic.CompilerServicesStandardModuleAttributeHideModuleNameAttributeSystem.ComponentModel.DesignHelpKeywordAttributeSystem.Runtime.CompilerServicesRuntimeHelpersGetObjectValueRuntimeTypeHandleGetTypeFromHandleActivatorCreateInstanceMyGroupCollectionAttributeget_Valueset_ValueSystem.Runtime.InteropServicesComVisibleAttributeCompilationRelaxationsAttributeRuntimeCompatibilityAttributeMTTestLib3MTTestLib3.Dll 1NGqZz\V4?_ :        0 (  ! %!% -  MyTemplate10.0.0.0   My.ApplicationMy.WebServices My.Computer My.UserI  a4System.Web.Services.Protocols.SoapHttpClientProtocolCreate__Instance__Dispose__Instance__   !% TWrapNonExceptionThrows// /_CorDllMainmscoree.dll% @0HX@TT4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfo000004b0,FileDescription 0FileVersion0.0.0.0@InternalNameMTTestLib3.Dll(LegalCopyright HOriginalFilenameMTTestLib3.Dll4ProductVersion0.0.0.08Assembly Version0.0.0.0 ?
MZ@ !L!This program cannot be run in DOS mode. $PELUśL! / @@ @/K@`  H.text  `.rsrc@@@.reloc `@B/H@"` ( *( *s s s s *0~o +*0~o +*0~o +*0~o +*0( ( +*0 ( +*0( +*0 ( +*0 - (+ ++ +*0 *( *0, { o -(+ { o  +*J( s } *( *0  +*0  +*0 +*BSJB v4.0.30319ld#~#Strings #US #GUID h#BlobW %3&    E Eu9& xQ < U)7:7 E7 O ] x 1 11-1S:1xG!TP X `   !( J5 hB Fc!Fh4!lP!Fqh!x!!! !!"|"," Qai$,4<$ , 4 < qy fch)*sqFDTLpLzL9)H.>.G@+@CCI cciY+{s4++$++ + @@+``++++++ koz*/4OTEY^^  uu j -- <Module>mscorlibMicrosoft.VisualBasicMyApplicationMyMyComputerMyProjectMyWebServicesThreadSafeObjectProvider`1Class5Microsoft.VisualBasic.ApplicationServicesApplicationBase.ctorMicrosoft.VisualBasic.DevicesComputerSystemObject.cctorget_Computerm_ComputerObjectProviderget_Applicationm_AppObjectProviderUserget_Userm_UserObjectProviderget_WebServicesm_MyWebServicesObjectProviderApplicationWebServicesEqualsoGetHashCodeTypeGetTypeToStringCreate__Instance__TinstanceDispose__Instance__get_GetInstanceMicrosoft.VisualBasic.MyServices.InternalContextValue`1m_ContextGetInstanceMTTestLib1Class1Foo1Class2Foo2MTTestLib2Class4Foo3Bar1Bar2Bar3System.ComponentModelEditorBrowsableAttributeEditorBrowsableStateSystem.CodeDom.CompilerGeneratedCodeAttributeSystem.DiagnosticsDebuggerHiddenAttributeMicrosoft.VisualBasic.CompilerServicesStandardModuleAttributeHideModuleNameAttributeSystem.ComponentModel.DesignHelpKeywordAttributeSystem.Runtime.CompilerServicesRuntimeHelpersGetObjectValueRuntimeTypeHandleGetTypeFromHandleActivatorCreateInstanceMyGroupCollectionAttributeget_Valueset_ValueSystem.Runtime.InteropServicesComVisibleAttributeCompilationRelaxationsAttributeRuntimeCompatibilityAttributeMTTestLib3MTTestLib3.Dll 1NGqZz\V4?_ :        0 (  ! %!% -  MyTemplate10.0.0.0   My.ApplicationMy.WebServices My.Computer My.UserI  a4System.Web.Services.Protocols.SoapHttpClientProtocolCreate__Instance__Dispose__Instance__   !% TWrapNonExceptionThrows// /_CorDllMainmscoree.dll% @0HX@TT4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfo000004b0,FileDescription 0FileVersion0.0.0.0@InternalNameMTTestLib3.Dll(LegalCopyright HOriginalFilenameMTTestLib3.Dll4ProductVersion0.0.0.08Assembly Version0.0.0.0 ?
-1
dotnet/roslyn
55,409
Use FixedSize API
tmat
2021-08-04T19:30:40Z
2021-08-04T21:53:46Z
e0112742bff208dd0546de45e36f7b52058a45a3
c90bf0ec986010051662c8e1fbc872c2fd86bc4e
Use FixedSize API.
./src/EditorFeatures/Test2/IntelliSense/VisualBasicCompletionCommandHandlerTests_DateAndTime.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Globalization Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense <[UseExportProvider]> Public Class VisualBasicCompletionCommandHandlerTests_DateAndTime <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ExplicitInvoke() As Task Using state = TestStateFactory.CreateVisualBasicTestState( <Document><![CDATA[ class c sub goo(d As Date) d.ToString("$$") end sub end class ]]></Document>) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("G", inlineDescription:=FeaturesResources.general_long_date_time) state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("d.ToString(""G"")", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ExplicitInvoke_OverwriteExisting() As Task Using state = TestStateFactory.CreateVisualBasicTestState( <Document><![CDATA[ class c sub goo(d As Date) d.ToString(":ff$$") end sub end class ]]></Document>) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("ff") state.SendDownKey() Await state.AssertSelectedCompletionItem("FF") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("d.ToString("":FF"")", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TypeChar_BeginningOfWord() As Task Using state = TestStateFactory.CreateVisualBasicTestState( <Document><![CDATA[ class c sub goo(d As Date) d.ToString("$$") end sub end class ]]></Document>) state.SendTypeChars("f") Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem("f") End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TypeChar_MiddleOfWord() As Task Using state = TestStateFactory.CreateVisualBasicTestState( <Document><![CDATA[ class c sub goo(d As Date) d.ToString("f$$") end sub end class ]]></Document>) state.SendTypeChars("f") Await state.AssertNoCompletionSession() End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestExample1() As Task Using state = TestStateFactory.CreateVisualBasicTestState( <Document><![CDATA[ class c sub goo(d As Date) d.ToString("hh:mm:$$") end sub end class ]]></Document>) state.SendInvokeCompletionList() state.SendTypeChars("ss") Await state.AssertSelectedCompletionItem("ss", inlineDescription:=FeaturesResources.second_2_digits) Dim description = Await state.GetSelectedItemDescriptionAsync() Dim text = description.Text If CultureInfo.CurrentCulture.Name <> "en-US" Then Assert.Contains($"hh:mm:ss (en-US) → 01:45:30", text) Assert.Contains($"hh:mm:ss ({CultureInfo.CurrentCulture.Name}) → 01:45:30", text) Else Assert.Contains("hh:mm:ss → 01:45:30", text) End If End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ExplicitInvoke_StringInterpolation() As Task Using state = TestStateFactory.CreateVisualBasicTestState( <Document><![CDATA[ class c sub goo(d As Date) Dim str = $"Text {d:$$}" end sub end class ]]></Document>) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("G", inlineDescription:=FeaturesResources.general_long_date_time) state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("Dim str = $""Text {d:G}""", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ExplicitInvoke_OverwriteExisting_StringInterpolation() As Task Using state = TestStateFactory.CreateVisualBasicTestState( <Document><![CDATA[ class c sub goo(d As Date) Dim str = $"Text {d:ff$$}" end sub end class ]]></Document>) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("ff") state.SendDownKey() Await state.AssertSelectedCompletionItem("FF") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("Dim str = $""Text {d:FF}""", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TypeChar_BeginningOfWord_StringInterpolation() As Task Using state = TestStateFactory.CreateVisualBasicTestState( <Document><![CDATA[ class c sub goo(d As Date) Dim str = $"Text {d:$$}" end sub end class ]]></Document>) state.SendTypeChars("f") Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem("f") End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestExample1_StringInterpolation() As Task Using state = TestStateFactory.CreateVisualBasicTestState( <Document><![CDATA[ class c sub goo(d As Date) Dim str = $"Text {d:hh:mm:$$}" end sub end class ]]></Document>) state.SendInvokeCompletionList() state.SendTypeChars("ss") Await state.AssertSelectedCompletionItem("ss", inlineDescription:=FeaturesResources.second_2_digits) Dim description = Await state.GetSelectedItemDescriptionAsync() Dim text = description.Text If CultureInfo.CurrentCulture.Name <> "en-US" Then Assert.Contains($"hh:mm:ss (en-US) → 01:45:30", text) Assert.Contains($"hh:mm:ss ({CultureInfo.CurrentCulture.Name}) → 01:45:30", text) Else Assert.Contains("hh:mm:ss → 01:45:30", text) End If End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TypeChar_MiddleOfWord_StringInterpolation() As Task Using state = TestStateFactory.CreateVisualBasicTestState( <Document><![CDATA[ class c sub goo(d As Date) Dim str = $"Text {date:f$$}" end sub end class ]]></Document>) state.SendTypeChars("f") Await state.AssertNoCompletionSession() End Using End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Globalization Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense <[UseExportProvider]> Public Class VisualBasicCompletionCommandHandlerTests_DateAndTime <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ExplicitInvoke() As Task Using state = TestStateFactory.CreateVisualBasicTestState( <Document><![CDATA[ class c sub goo(d As Date) d.ToString("$$") end sub end class ]]></Document>) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("G", inlineDescription:=FeaturesResources.general_long_date_time) state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("d.ToString(""G"")", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ExplicitInvoke_OverwriteExisting() As Task Using state = TestStateFactory.CreateVisualBasicTestState( <Document><![CDATA[ class c sub goo(d As Date) d.ToString(":ff$$") end sub end class ]]></Document>) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("ff") state.SendDownKey() Await state.AssertSelectedCompletionItem("FF") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("d.ToString("":FF"")", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TypeChar_BeginningOfWord() As Task Using state = TestStateFactory.CreateVisualBasicTestState( <Document><![CDATA[ class c sub goo(d As Date) d.ToString("$$") end sub end class ]]></Document>) state.SendTypeChars("f") Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem("f") End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TypeChar_MiddleOfWord() As Task Using state = TestStateFactory.CreateVisualBasicTestState( <Document><![CDATA[ class c sub goo(d As Date) d.ToString("f$$") end sub end class ]]></Document>) state.SendTypeChars("f") Await state.AssertNoCompletionSession() End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestExample1() As Task Using state = TestStateFactory.CreateVisualBasicTestState( <Document><![CDATA[ class c sub goo(d As Date) d.ToString("hh:mm:$$") end sub end class ]]></Document>) state.SendInvokeCompletionList() state.SendTypeChars("ss") Await state.AssertSelectedCompletionItem("ss", inlineDescription:=FeaturesResources.second_2_digits) Dim description = Await state.GetSelectedItemDescriptionAsync() Dim text = description.Text If CultureInfo.CurrentCulture.Name <> "en-US" Then Assert.Contains($"hh:mm:ss (en-US) → 01:45:30", text) Assert.Contains($"hh:mm:ss ({CultureInfo.CurrentCulture.Name}) → 01:45:30", text) Else Assert.Contains("hh:mm:ss → 01:45:30", text) End If End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ExplicitInvoke_StringInterpolation() As Task Using state = TestStateFactory.CreateVisualBasicTestState( <Document><![CDATA[ class c sub goo(d As Date) Dim str = $"Text {d:$$}" end sub end class ]]></Document>) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("G", inlineDescription:=FeaturesResources.general_long_date_time) state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("Dim str = $""Text {d:G}""", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ExplicitInvoke_OverwriteExisting_StringInterpolation() As Task Using state = TestStateFactory.CreateVisualBasicTestState( <Document><![CDATA[ class c sub goo(d As Date) Dim str = $"Text {d:ff$$}" end sub end class ]]></Document>) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("ff") state.SendDownKey() Await state.AssertSelectedCompletionItem("FF") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("Dim str = $""Text {d:FF}""", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TypeChar_BeginningOfWord_StringInterpolation() As Task Using state = TestStateFactory.CreateVisualBasicTestState( <Document><![CDATA[ class c sub goo(d As Date) Dim str = $"Text {d:$$}" end sub end class ]]></Document>) state.SendTypeChars("f") Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem("f") End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestExample1_StringInterpolation() As Task Using state = TestStateFactory.CreateVisualBasicTestState( <Document><![CDATA[ class c sub goo(d As Date) Dim str = $"Text {d:hh:mm:$$}" end sub end class ]]></Document>) state.SendInvokeCompletionList() state.SendTypeChars("ss") Await state.AssertSelectedCompletionItem("ss", inlineDescription:=FeaturesResources.second_2_digits) Dim description = Await state.GetSelectedItemDescriptionAsync() Dim text = description.Text If CultureInfo.CurrentCulture.Name <> "en-US" Then Assert.Contains($"hh:mm:ss (en-US) → 01:45:30", text) Assert.Contains($"hh:mm:ss ({CultureInfo.CurrentCulture.Name}) → 01:45:30", text) Else Assert.Contains("hh:mm:ss → 01:45:30", text) End If End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TypeChar_MiddleOfWord_StringInterpolation() As Task Using state = TestStateFactory.CreateVisualBasicTestState( <Document><![CDATA[ class c sub goo(d As Date) Dim str = $"Text {date:f$$}" end sub end class ]]></Document>) state.SendTypeChars("f") Await state.AssertNoCompletionSession() End Using End Function End Class End Namespace
-1
dotnet/roslyn
55,409
Use FixedSize API
tmat
2021-08-04T19:30:40Z
2021-08-04T21:53:46Z
e0112742bff208dd0546de45e36f7b52058a45a3
c90bf0ec986010051662c8e1fbc872c2fd86bc4e
Use FixedSize API.
./src/VisualStudio/Core/Impl/CodeModel/FileCodeModel_Events.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { public sealed partial class FileCodeModel { private const int ElementAddedDispId = 1; private const int ElementChangedDispId = 2; private const int ElementDeletedDispId = 3; private const int ElementDeletedDispId2 = 4; public void FireEvents() { _ = _codeElementTable.CleanUpDeadObjectsAsync(State.ProjectCodeModelFactory.Listener).ReportNonFatalErrorAsync(); if (this.IsZombied) { // file is removed from the solution. this can happen if a fireevent is enqueued to foreground notification service // but the file itself is removed from the solution before it has a chance to run return; } if (!TryGetDocument(out var document)) { // file is removed from the solution. this can happen if a fireevent is enqueued to foreground notification service // but the file itself is removed from the solution before it has a chance to run return; } // TODO(DustinCa): Enqueue unknown change event if a file is closed without being saved. var oldTree = _lastSyntaxTree; var newTree = document.GetSyntaxTreeSynchronously(CancellationToken.None); _lastSyntaxTree = newTree; if (oldTree == newTree || oldTree.IsEquivalentTo(newTree, topLevel: true)) { return; } var eventQueue = this.CodeModelService.CollectCodeModelEvents(oldTree, newTree); if (eventQueue.Count == 0) { return; } var projectCodeModel = this.State.ProjectCodeModelFactory.GetProjectCodeModel(document.Project.Id); if (projectCodeModel == null) { return; } if (!projectCodeModel.TryGetCachedFileCodeModel(this.Workspace.GetFilePath(GetDocumentId()), out _)) { return; } var extensibility = (EnvDTE80.IVsExtensibility2)this.State.ServiceProvider.GetService(typeof(EnvDTE.IVsExtensibility)); if (extensibility == null) return; foreach (var codeModelEvent in eventQueue) { GetElementsForCodeModelEvent(codeModelEvent, out var element, out var parentElement); if (codeModelEvent.Type == CodeModelEventType.Add) { extensibility.FireCodeModelEvent(ElementAddedDispId, element, EnvDTE80.vsCMChangeKind.vsCMChangeKindUnknown); } else if (codeModelEvent.Type == CodeModelEventType.Remove) { extensibility.FireCodeModelEvent3(ElementDeletedDispId2, parentElement, element, EnvDTE80.vsCMChangeKind.vsCMChangeKindUnknown); extensibility.FireCodeModelEvent(ElementDeletedDispId, element, EnvDTE80.vsCMChangeKind.vsCMChangeKindUnknown); } else if (codeModelEvent.Type.IsChange()) { extensibility.FireCodeModelEvent(ElementChangedDispId, element, ConvertToChangeKind(codeModelEvent.Type)); } else { Debug.Fail("Invalid event type: " + codeModelEvent.Type); } } return; } private EnvDTE80.vsCMChangeKind ConvertToChangeKind(CodeModelEventType eventType) { EnvDTE80.vsCMChangeKind result = 0; if ((eventType & CodeModelEventType.Rename) != 0) { result |= EnvDTE80.vsCMChangeKind.vsCMChangeKindRename; } if ((eventType & CodeModelEventType.Unknown) != 0) { result |= EnvDTE80.vsCMChangeKind.vsCMChangeKindUnknown; } if ((eventType & CodeModelEventType.BaseChange) != 0) { result |= EnvDTE80.vsCMChangeKind.vsCMChangeKindBaseChange; } if ((eventType & CodeModelEventType.TypeRefChange) != 0) { result |= EnvDTE80.vsCMChangeKind.vsCMChangeKindTypeRefChange; } if ((eventType & CodeModelEventType.SigChange) != 0) { result |= EnvDTE80.vsCMChangeKind.vsCMChangeKindSignatureChange; } if ((eventType & CodeModelEventType.ArgChange) != 0) { result |= EnvDTE80.vsCMChangeKind.vsCMChangeKindArgumentChange; } return result; } // internal for testing internal void GetElementsForCodeModelEvent(CodeModelEvent codeModelEvent, out EnvDTE.CodeElement element, out object parentElement) { parentElement = GetParentElementForCodeModelEvent(codeModelEvent); if (codeModelEvent.Node == null) { element = this.CodeModelService.CreateUnknownRootNamespaceCodeElement(this.State, this); } else if (this.CodeModelService.IsParameterNode(codeModelEvent.Node)) { element = GetParameterElementForCodeModelEvent(codeModelEvent, parentElement); } else if (this.CodeModelService.IsAttributeNode(codeModelEvent.Node)) { element = GetAttributeElementForCodeModelEvent(codeModelEvent, parentElement); } else if (this.CodeModelService.IsAttributeArgumentNode(codeModelEvent.Node)) { element = GetAttributeArgumentElementForCodeModelEvent(codeModelEvent, parentElement); } else { if (codeModelEvent.Type == CodeModelEventType.Remove) { element = this.CodeModelService.CreateUnknownCodeElement(this.State, this, codeModelEvent.Node); } else { element = this.GetOrCreateCodeElement<EnvDTE.CodeElement>(codeModelEvent.Node); } } if (element == null) { Debug.Fail("We should have created an element for this event!"); } Debug.Assert(codeModelEvent.Type != CodeModelEventType.Remove || parentElement != null); } private object GetParentElementForCodeModelEvent(CodeModelEvent codeModelEvent) { if (this.CodeModelService.IsParameterNode(codeModelEvent.Node) || this.CodeModelService.IsAttributeArgumentNode(codeModelEvent.Node)) { if (codeModelEvent.ParentNode != null) { return this.GetOrCreateCodeElement<EnvDTE.CodeElement>(codeModelEvent.ParentNode); } } else if (this.CodeModelService.IsAttributeNode(codeModelEvent.Node)) { if (codeModelEvent.ParentNode != null) { return this.GetOrCreateCodeElement<EnvDTE.CodeElement>(codeModelEvent.ParentNode); } else { return this; } } else if (codeModelEvent.Type == CodeModelEventType.Remove) { if (codeModelEvent.ParentNode != null && codeModelEvent.ParentNode.Parent != null) { return this.GetOrCreateCodeElement<EnvDTE.CodeElement>(codeModelEvent.ParentNode); } else { return this; } } return null; } private EnvDTE.CodeElement GetParameterElementForCodeModelEvent(CodeModelEvent codeModelEvent, object parentElement) => parentElement switch { EnvDTE.CodeDelegate parentDelegate => GetParameterElementForCodeModelEvent(codeModelEvent, parentDelegate.Parameters, parentElement), EnvDTE.CodeFunction parentFunction => GetParameterElementForCodeModelEvent(codeModelEvent, parentFunction.Parameters, parentElement), EnvDTE80.CodeProperty2 parentProperty => GetParameterElementForCodeModelEvent(codeModelEvent, parentProperty.Parameters, parentElement), _ => null, }; private EnvDTE.CodeElement GetParameterElementForCodeModelEvent(CodeModelEvent codeModelEvent, EnvDTE.CodeElements parentParameters, object parentElement) { if (parentParameters == null) { return null; } var parameterName = this.CodeModelService.GetName(codeModelEvent.Node); if (codeModelEvent.Type == CodeModelEventType.Remove) { var parentCodeElement = ComAggregate.TryGetManagedObject<AbstractCodeMember>(parentElement); if (parentCodeElement != null) { return (EnvDTE.CodeElement)CodeParameter.Create(this.State, parentCodeElement, parameterName); } } else { return parentParameters.Item(parameterName); } return null; } private EnvDTE.CodeElement GetAttributeElementForCodeModelEvent(CodeModelEvent codeModelEvent, object parentElement) { var node = codeModelEvent.Node; var parentNode = codeModelEvent.ParentNode; var eventType = codeModelEvent.Type; switch (parentElement) { case EnvDTE.CodeType parentType: return GetAttributeElementForCodeModelEvent(node, parentNode, eventType, parentType.Attributes, parentElement); case EnvDTE.CodeFunction parentFunction: return GetAttributeElementForCodeModelEvent(node, parentNode, eventType, parentFunction.Attributes, parentElement); case EnvDTE.CodeProperty parentProperty: return GetAttributeElementForCodeModelEvent(node, parentNode, eventType, parentProperty.Attributes, parentElement); case EnvDTE80.CodeEvent parentEvent: return GetAttributeElementForCodeModelEvent(node, parentNode, eventType, parentEvent.Attributes, parentElement); case EnvDTE.CodeVariable parentVariable: return GetAttributeElementForCodeModelEvent(node, parentNode, eventType, parentVariable.Attributes, parentElement); case EnvDTE.FileCodeModel parentFileCodeModel: { var fileCodeModel = ComAggregate.TryGetManagedObject<FileCodeModel>(parentElement); parentNode = fileCodeModel.GetSyntaxRoot(); return GetAttributeElementForCodeModelEvent(node, parentNode, eventType, parentFileCodeModel.CodeElements, parentElement); } } return null; } private EnvDTE.CodeElement GetAttributeElementForCodeModelEvent(SyntaxNode node, SyntaxNode parentNode, CodeModelEventType eventType, EnvDTE.CodeElements elementsToSearch, object parentObject) { if (elementsToSearch == null) { return null; } CodeModelService.GetAttributeNameAndOrdinal(parentNode, node, out var name, out var ordinal); if (eventType == CodeModelEventType.Remove) { if (parentObject is EnvDTE.CodeElement) { var parentCodeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(parentObject); if (parentCodeElement != null) { return (EnvDTE.CodeElement)CodeAttribute.Create(this.State, this, parentCodeElement, name, ordinal); } } else if (parentObject is EnvDTE.FileCodeModel) { var parentFileCodeModel = ComAggregate.TryGetManagedObject<FileCodeModel>(parentObject); if (parentFileCodeModel != null && parentFileCodeModel == this) { return (EnvDTE.CodeElement)CodeAttribute.Create(this.State, this, null, name, ordinal); } } } else { var testOrdinal = 0; foreach (EnvDTE.CodeElement element in elementsToSearch) { if (element.Kind != EnvDTE.vsCMElement.vsCMElementAttribute) { continue; } if (element.Name == name) { if (ordinal == testOrdinal) { return element; } testOrdinal++; } } } return null; } private EnvDTE.CodeElement GetAttributeArgumentElementForCodeModelEvent(CodeModelEvent codeModelEvent, object parentElement) { if (parentElement is EnvDTE80.CodeAttribute2 parentAttribute) { return GetAttributeArgumentForCodeModelEvent(codeModelEvent, parentAttribute.Arguments, parentElement); } return null; } private EnvDTE.CodeElement GetAttributeArgumentForCodeModelEvent(CodeModelEvent codeModelEvent, EnvDTE.CodeElements parentAttributeArguments, object parentElement) { if (parentAttributeArguments == null) { return null; } CodeModelService.GetAttributeArgumentParentAndIndex(codeModelEvent.Node, out _, out var ordinal); if (codeModelEvent.Type == CodeModelEventType.Remove) { var parentCodeElement = ComAggregate.TryGetManagedObject<CodeAttribute>(parentElement); if (parentCodeElement != null) { return (EnvDTE.CodeElement)CodeAttributeArgument.Create(this.State, parentCodeElement, ordinal); } } else { return parentAttributeArguments.Item(ordinal + 1); // Needs to be 1-based to call back into code model } return null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { public sealed partial class FileCodeModel { private const int ElementAddedDispId = 1; private const int ElementChangedDispId = 2; private const int ElementDeletedDispId = 3; private const int ElementDeletedDispId2 = 4; public void FireEvents() { _ = _codeElementTable.CleanUpDeadObjectsAsync(State.ProjectCodeModelFactory.Listener).ReportNonFatalErrorAsync(); if (this.IsZombied) { // file is removed from the solution. this can happen if a fireevent is enqueued to foreground notification service // but the file itself is removed from the solution before it has a chance to run return; } if (!TryGetDocument(out var document)) { // file is removed from the solution. this can happen if a fireevent is enqueued to foreground notification service // but the file itself is removed from the solution before it has a chance to run return; } // TODO(DustinCa): Enqueue unknown change event if a file is closed without being saved. var oldTree = _lastSyntaxTree; var newTree = document.GetSyntaxTreeSynchronously(CancellationToken.None); _lastSyntaxTree = newTree; if (oldTree == newTree || oldTree.IsEquivalentTo(newTree, topLevel: true)) { return; } var eventQueue = this.CodeModelService.CollectCodeModelEvents(oldTree, newTree); if (eventQueue.Count == 0) { return; } var projectCodeModel = this.State.ProjectCodeModelFactory.GetProjectCodeModel(document.Project.Id); if (projectCodeModel == null) { return; } if (!projectCodeModel.TryGetCachedFileCodeModel(this.Workspace.GetFilePath(GetDocumentId()), out _)) { return; } var extensibility = (EnvDTE80.IVsExtensibility2)this.State.ServiceProvider.GetService(typeof(EnvDTE.IVsExtensibility)); if (extensibility == null) return; foreach (var codeModelEvent in eventQueue) { GetElementsForCodeModelEvent(codeModelEvent, out var element, out var parentElement); if (codeModelEvent.Type == CodeModelEventType.Add) { extensibility.FireCodeModelEvent(ElementAddedDispId, element, EnvDTE80.vsCMChangeKind.vsCMChangeKindUnknown); } else if (codeModelEvent.Type == CodeModelEventType.Remove) { extensibility.FireCodeModelEvent3(ElementDeletedDispId2, parentElement, element, EnvDTE80.vsCMChangeKind.vsCMChangeKindUnknown); extensibility.FireCodeModelEvent(ElementDeletedDispId, element, EnvDTE80.vsCMChangeKind.vsCMChangeKindUnknown); } else if (codeModelEvent.Type.IsChange()) { extensibility.FireCodeModelEvent(ElementChangedDispId, element, ConvertToChangeKind(codeModelEvent.Type)); } else { Debug.Fail("Invalid event type: " + codeModelEvent.Type); } } return; } private EnvDTE80.vsCMChangeKind ConvertToChangeKind(CodeModelEventType eventType) { EnvDTE80.vsCMChangeKind result = 0; if ((eventType & CodeModelEventType.Rename) != 0) { result |= EnvDTE80.vsCMChangeKind.vsCMChangeKindRename; } if ((eventType & CodeModelEventType.Unknown) != 0) { result |= EnvDTE80.vsCMChangeKind.vsCMChangeKindUnknown; } if ((eventType & CodeModelEventType.BaseChange) != 0) { result |= EnvDTE80.vsCMChangeKind.vsCMChangeKindBaseChange; } if ((eventType & CodeModelEventType.TypeRefChange) != 0) { result |= EnvDTE80.vsCMChangeKind.vsCMChangeKindTypeRefChange; } if ((eventType & CodeModelEventType.SigChange) != 0) { result |= EnvDTE80.vsCMChangeKind.vsCMChangeKindSignatureChange; } if ((eventType & CodeModelEventType.ArgChange) != 0) { result |= EnvDTE80.vsCMChangeKind.vsCMChangeKindArgumentChange; } return result; } // internal for testing internal void GetElementsForCodeModelEvent(CodeModelEvent codeModelEvent, out EnvDTE.CodeElement element, out object parentElement) { parentElement = GetParentElementForCodeModelEvent(codeModelEvent); if (codeModelEvent.Node == null) { element = this.CodeModelService.CreateUnknownRootNamespaceCodeElement(this.State, this); } else if (this.CodeModelService.IsParameterNode(codeModelEvent.Node)) { element = GetParameterElementForCodeModelEvent(codeModelEvent, parentElement); } else if (this.CodeModelService.IsAttributeNode(codeModelEvent.Node)) { element = GetAttributeElementForCodeModelEvent(codeModelEvent, parentElement); } else if (this.CodeModelService.IsAttributeArgumentNode(codeModelEvent.Node)) { element = GetAttributeArgumentElementForCodeModelEvent(codeModelEvent, parentElement); } else { if (codeModelEvent.Type == CodeModelEventType.Remove) { element = this.CodeModelService.CreateUnknownCodeElement(this.State, this, codeModelEvent.Node); } else { element = this.GetOrCreateCodeElement<EnvDTE.CodeElement>(codeModelEvent.Node); } } if (element == null) { Debug.Fail("We should have created an element for this event!"); } Debug.Assert(codeModelEvent.Type != CodeModelEventType.Remove || parentElement != null); } private object GetParentElementForCodeModelEvent(CodeModelEvent codeModelEvent) { if (this.CodeModelService.IsParameterNode(codeModelEvent.Node) || this.CodeModelService.IsAttributeArgumentNode(codeModelEvent.Node)) { if (codeModelEvent.ParentNode != null) { return this.GetOrCreateCodeElement<EnvDTE.CodeElement>(codeModelEvent.ParentNode); } } else if (this.CodeModelService.IsAttributeNode(codeModelEvent.Node)) { if (codeModelEvent.ParentNode != null) { return this.GetOrCreateCodeElement<EnvDTE.CodeElement>(codeModelEvent.ParentNode); } else { return this; } } else if (codeModelEvent.Type == CodeModelEventType.Remove) { if (codeModelEvent.ParentNode != null && codeModelEvent.ParentNode.Parent != null) { return this.GetOrCreateCodeElement<EnvDTE.CodeElement>(codeModelEvent.ParentNode); } else { return this; } } return null; } private EnvDTE.CodeElement GetParameterElementForCodeModelEvent(CodeModelEvent codeModelEvent, object parentElement) => parentElement switch { EnvDTE.CodeDelegate parentDelegate => GetParameterElementForCodeModelEvent(codeModelEvent, parentDelegate.Parameters, parentElement), EnvDTE.CodeFunction parentFunction => GetParameterElementForCodeModelEvent(codeModelEvent, parentFunction.Parameters, parentElement), EnvDTE80.CodeProperty2 parentProperty => GetParameterElementForCodeModelEvent(codeModelEvent, parentProperty.Parameters, parentElement), _ => null, }; private EnvDTE.CodeElement GetParameterElementForCodeModelEvent(CodeModelEvent codeModelEvent, EnvDTE.CodeElements parentParameters, object parentElement) { if (parentParameters == null) { return null; } var parameterName = this.CodeModelService.GetName(codeModelEvent.Node); if (codeModelEvent.Type == CodeModelEventType.Remove) { var parentCodeElement = ComAggregate.TryGetManagedObject<AbstractCodeMember>(parentElement); if (parentCodeElement != null) { return (EnvDTE.CodeElement)CodeParameter.Create(this.State, parentCodeElement, parameterName); } } else { return parentParameters.Item(parameterName); } return null; } private EnvDTE.CodeElement GetAttributeElementForCodeModelEvent(CodeModelEvent codeModelEvent, object parentElement) { var node = codeModelEvent.Node; var parentNode = codeModelEvent.ParentNode; var eventType = codeModelEvent.Type; switch (parentElement) { case EnvDTE.CodeType parentType: return GetAttributeElementForCodeModelEvent(node, parentNode, eventType, parentType.Attributes, parentElement); case EnvDTE.CodeFunction parentFunction: return GetAttributeElementForCodeModelEvent(node, parentNode, eventType, parentFunction.Attributes, parentElement); case EnvDTE.CodeProperty parentProperty: return GetAttributeElementForCodeModelEvent(node, parentNode, eventType, parentProperty.Attributes, parentElement); case EnvDTE80.CodeEvent parentEvent: return GetAttributeElementForCodeModelEvent(node, parentNode, eventType, parentEvent.Attributes, parentElement); case EnvDTE.CodeVariable parentVariable: return GetAttributeElementForCodeModelEvent(node, parentNode, eventType, parentVariable.Attributes, parentElement); case EnvDTE.FileCodeModel parentFileCodeModel: { var fileCodeModel = ComAggregate.TryGetManagedObject<FileCodeModel>(parentElement); parentNode = fileCodeModel.GetSyntaxRoot(); return GetAttributeElementForCodeModelEvent(node, parentNode, eventType, parentFileCodeModel.CodeElements, parentElement); } } return null; } private EnvDTE.CodeElement GetAttributeElementForCodeModelEvent(SyntaxNode node, SyntaxNode parentNode, CodeModelEventType eventType, EnvDTE.CodeElements elementsToSearch, object parentObject) { if (elementsToSearch == null) { return null; } CodeModelService.GetAttributeNameAndOrdinal(parentNode, node, out var name, out var ordinal); if (eventType == CodeModelEventType.Remove) { if (parentObject is EnvDTE.CodeElement) { var parentCodeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(parentObject); if (parentCodeElement != null) { return (EnvDTE.CodeElement)CodeAttribute.Create(this.State, this, parentCodeElement, name, ordinal); } } else if (parentObject is EnvDTE.FileCodeModel) { var parentFileCodeModel = ComAggregate.TryGetManagedObject<FileCodeModel>(parentObject); if (parentFileCodeModel != null && parentFileCodeModel == this) { return (EnvDTE.CodeElement)CodeAttribute.Create(this.State, this, null, name, ordinal); } } } else { var testOrdinal = 0; foreach (EnvDTE.CodeElement element in elementsToSearch) { if (element.Kind != EnvDTE.vsCMElement.vsCMElementAttribute) { continue; } if (element.Name == name) { if (ordinal == testOrdinal) { return element; } testOrdinal++; } } } return null; } private EnvDTE.CodeElement GetAttributeArgumentElementForCodeModelEvent(CodeModelEvent codeModelEvent, object parentElement) { if (parentElement is EnvDTE80.CodeAttribute2 parentAttribute) { return GetAttributeArgumentForCodeModelEvent(codeModelEvent, parentAttribute.Arguments, parentElement); } return null; } private EnvDTE.CodeElement GetAttributeArgumentForCodeModelEvent(CodeModelEvent codeModelEvent, EnvDTE.CodeElements parentAttributeArguments, object parentElement) { if (parentAttributeArguments == null) { return null; } CodeModelService.GetAttributeArgumentParentAndIndex(codeModelEvent.Node, out _, out var ordinal); if (codeModelEvent.Type == CodeModelEventType.Remove) { var parentCodeElement = ComAggregate.TryGetManagedObject<CodeAttribute>(parentElement); if (parentCodeElement != null) { return (EnvDTE.CodeElement)CodeAttributeArgument.Create(this.State, parentCodeElement, ordinal); } } else { return parentAttributeArguments.Item(ordinal + 1); // Needs to be 1-based to call back into code model } return null; } } }
-1
dotnet/roslyn
55,408
Update package references
CyrusNajmabadi
2021-08-04T19:12:45Z
2021-08-04T22:34:08Z
967cf7cf7be8478cce7cda728217eab8504f2863
d41ae79bb1a3f0deb2de2f3d67c976f795da9563
Update package references.
./src/Dependencies/CodeAnalysis.Debugging/Microsoft.CodeAnalysis.Debugging.Package.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworks>netstandard1.3;net45</TargetFrameworks> <GenerateDocumentationFile>false</GenerateDocumentationFile> <DebugType>none</DebugType> <GenerateDependencyFile>false</GenerateDependencyFile> <!-- NuGet --> <IsPackable>true</IsPackable> <IsSourcePackage>true</IsSourcePackage> <PackageId>Microsoft.CodeAnalysis.Debugging</PackageId> <IncludeBuildOutput>false</IncludeBuildOutput> <PackageDescription> Package containing sources of Microsoft .NET Compiler Platform ("Roslyn") debug information encoders and decoders. </PackageDescription> <!-- Remove once https://github.com/NuGet/Home/issues/8583 is fixed --> <NoWarn>$(NoWarn);NU5128</NoWarn> </PropertyGroup> <ItemGroup> <PackageReference Include="System.Collections.Immutable" Version="$(SystemCollectionsImmutableVersion)" /> <PackageReference Include="System.Reflection.Metadata" Version="$(SystemReflectionMetadataVersion)" /> <PackageReference Include="System.ValueTuple" Version="$(SystemValueTupleVersion)" /> <ProjectReference Include="..\PooledObjects\Microsoft.CodeAnalysis.PooledObjects.Package.csproj" /> </ItemGroup> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworks>netstandard1.3;net45</TargetFrameworks> <GenerateDocumentationFile>false</GenerateDocumentationFile> <DebugType>none</DebugType> <GenerateDependencyFile>false</GenerateDependencyFile> <!-- NuGet --> <IsPackable>true</IsPackable> <IsSourcePackage>true</IsSourcePackage> <PackageId>Microsoft.CodeAnalysis.Debugging</PackageId> <IncludeBuildOutput>false</IncludeBuildOutput> <PackageDescription> Package containing sources of Microsoft .NET Compiler Platform ("Roslyn") debug information encoders and decoders. </PackageDescription> <!-- Remove once https://github.com/NuGet/Home/issues/8583 is fixed --> <NoWarn>$(NoWarn);NU5128</NoWarn> </PropertyGroup> <ItemGroup> <PackageReference Include="System.Collections.Immutable" Version="$(SystemCollectionsImmutableVersion)" /> <PackageReference Include="System.Reflection.Metadata" Version="$(SystemReflectionMetadataVersion)" /> <PackageReference Include="System.ValueTuple" Version="$(SystemValueTupleVersion)" /> <ProjectReference Include="..\PooledObjects\Microsoft.CodeAnalysis.PooledObjects.Package.csproj" /> <!-- Remove once https://github.com/dotnet/sdk/issues/19506 is resolved --> <PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="$(MicrosoftNETFrameworkReferenceAssembliesVersion)" /> </ItemGroup> </Project>
1
dotnet/roslyn
55,408
Update package references
CyrusNajmabadi
2021-08-04T19:12:45Z
2021-08-04T22:34:08Z
967cf7cf7be8478cce7cda728217eab8504f2863
d41ae79bb1a3f0deb2de2f3d67c976f795da9563
Update package references.
./src/Dependencies/PooledObjects/Microsoft.CodeAnalysis.PooledObjects.Package.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworks>netstandard1.3;net45</TargetFrameworks> <GenerateDocumentationFile>false</GenerateDocumentationFile> <DebugType>none</DebugType> <GenerateDependencyFile>false</GenerateDependencyFile> <!-- NuGet --> <IsPackable>true</IsPackable> <IsSourcePackage>true</IsSourcePackage> <PackageId>Microsoft.CodeAnalysis.PooledObjects</PackageId> <IncludeBuildOutput>false</IncludeBuildOutput> <PackageDescription> Package containing sources of Microsoft .NET Compiler Platform ("Roslyn") pooled objects. </PackageDescription> <!-- Remove once https://github.com/NuGet/Home/issues/8583 is fixed --> <NoWarn>$(NoWarn);NU5128</NoWarn> </PropertyGroup> <ItemGroup> <PackageReference Include="System.Collections.Immutable" Version="$(SystemCollectionsImmutableVersion)" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Debugging.Package"/> </ItemGroup> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworks>netstandard1.3;net45</TargetFrameworks> <GenerateDocumentationFile>false</GenerateDocumentationFile> <DebugType>none</DebugType> <GenerateDependencyFile>false</GenerateDependencyFile> <!-- NuGet --> <IsPackable>true</IsPackable> <IsSourcePackage>true</IsSourcePackage> <PackageId>Microsoft.CodeAnalysis.PooledObjects</PackageId> <IncludeBuildOutput>false</IncludeBuildOutput> <PackageDescription> Package containing sources of Microsoft .NET Compiler Platform ("Roslyn") pooled objects. </PackageDescription> <!-- Remove once https://github.com/NuGet/Home/issues/8583 is fixed --> <NoWarn>$(NoWarn);NU5128</NoWarn> </PropertyGroup> <ItemGroup> <PackageReference Include="System.Collections.Immutable" Version="$(SystemCollectionsImmutableVersion)" /> <!-- Remove once https://github.com/dotnet/sdk/issues/19506 is resolved --> <PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="$(MicrosoftNETFrameworkReferenceAssembliesVersion)" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Debugging.Package"/> </ItemGroup> </Project>
1
dotnet/roslyn
55,408
Update package references
CyrusNajmabadi
2021-08-04T19:12:45Z
2021-08-04T22:34:08Z
967cf7cf7be8478cce7cda728217eab8504f2863
d41ae79bb1a3f0deb2de2f3d67c976f795da9563
Update package references.
./src/ExpressionEvaluator/Core/Source/FunctionResolver/Microsoft.CodeAnalysis.FunctionResolver.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis.ExpressionEvaluator</RootNamespace> <AssemblyName>Microsoft.CodeAnalysis.ExpressionEvaluator.FunctionResolver</AssemblyName> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <!-- This component is deployed with remote debugger tools. It needs to work on .NET Framework 4.5 and Core CLR 1.0 (Windows OneCore) --> <TargetFrameworks>net45;netstandard1.3</TargetFrameworks> </PropertyGroup> <ItemGroup> <Compile Include="..\..\..\..\Compilers\Core\Portable\InternalUtilities\ExceptionUtilities.cs"> <Link>Compiler\ExceptionUtilities.cs</Link> </Compile> <Compile Include="..\..\..\..\Compilers\Core\Portable\MetadataReader\MetadataTypeCodeExtensions.cs"> <Link>Compiler\MetadataTypeCodeExtensions.cs</Link> </Compile> <Compile Include="..\..\..\..\Compilers\Core\Portable\SpecialType.cs"> <Link>Compiler\SpecialType.cs</Link> </Compile> <Compile Include="..\..\..\..\Compilers\Core\Portable\Symbols\WellKnownMemberNames.cs"> <Link>Compiler\WellKnownMemberNames.cs</Link> </Compile> <Compile Include="..\..\..\..\Compilers\Core\Portable\InternalUtilities\NullableAttributes.cs"> <Link>Compiler\NullableAttributes.cs</Link> </Compile> <Compile Include="..\..\..\..\Compilers\Core\Portable\InternalUtilities\RoslynString.cs"> <Link>Compiler\RoslynString.cs</Link> </Compile> <Compile Include="..\..\..\..\Compilers\Core\Portable\InternalUtilities\UnicodeCharacterUtilities.cs"> <Link>Compiler\UnicodeCharacterUtilities.cs</Link> </Compile> <Compile Include="..\..\..\..\Compilers\CSharp\Portable\Syntax\SyntaxKind.cs"> <Link>CSharp\Compiler\SyntaxKind.cs</Link> </Compile> <Compile Include="..\..\..\..\Compilers\CSharp\Portable\Syntax\SyntaxKindFacts.cs"> <Link>CSharp\Compiler\SyntaxKindFacts.cs</Link> </Compile> <Compile Include="..\ExpressionCompiler\DkmExceptionUtilities.cs"> <Link>ExpressionCompiler\DkmExceptionUtilities.cs</Link> </Compile> <VsdConfigXmlFiles Include="CSharp\FunctionResolver.vsdconfigxml" /> <VsdConfigXmlFiles Include="VisualBasic\FunctionResolver.vsdconfigxml" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.ExpressionEvaluator.FunctionResolver.UnitTests" /> </ItemGroup> <ItemGroup> <PackageReference Include="System.Collections.Immutable" Version="$(SystemCollectionsImmutableVersion)" /> <PackageReference Include="System.Reflection.Metadata" Version="$(SystemReflectionMetadataVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Debugger.Engine-implementation" Version="$(MicrosoftVisualStudioDebuggerEngineimplementationVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Debugger.Metadata-implementation"> <Version>$(MicrosoftVisualStudioDebuggerMetadataimplementationVersion)</Version> <ExcludeAssets>compile</ExcludeAssets> </PackageReference> </ItemGroup> <Import Project="$(RepositoryEngineeringDir)targets\Vsdconfig.targets" /> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis.ExpressionEvaluator</RootNamespace> <AssemblyName>Microsoft.CodeAnalysis.ExpressionEvaluator.FunctionResolver</AssemblyName> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <!-- This component is deployed with remote debugger tools. It needs to work on .NET Framework 4.5 and Core CLR 1.0 (Windows OneCore) --> <TargetFrameworks>net45;netstandard1.3</TargetFrameworks> </PropertyGroup> <ItemGroup> <Compile Include="..\..\..\..\Compilers\Core\Portable\InternalUtilities\ExceptionUtilities.cs"> <Link>Compiler\ExceptionUtilities.cs</Link> </Compile> <Compile Include="..\..\..\..\Compilers\Core\Portable\MetadataReader\MetadataTypeCodeExtensions.cs"> <Link>Compiler\MetadataTypeCodeExtensions.cs</Link> </Compile> <Compile Include="..\..\..\..\Compilers\Core\Portable\SpecialType.cs"> <Link>Compiler\SpecialType.cs</Link> </Compile> <Compile Include="..\..\..\..\Compilers\Core\Portable\Symbols\WellKnownMemberNames.cs"> <Link>Compiler\WellKnownMemberNames.cs</Link> </Compile> <Compile Include="..\..\..\..\Compilers\Core\Portable\InternalUtilities\NullableAttributes.cs"> <Link>Compiler\NullableAttributes.cs</Link> </Compile> <Compile Include="..\..\..\..\Compilers\Core\Portable\InternalUtilities\RoslynString.cs"> <Link>Compiler\RoslynString.cs</Link> </Compile> <Compile Include="..\..\..\..\Compilers\Core\Portable\InternalUtilities\UnicodeCharacterUtilities.cs"> <Link>Compiler\UnicodeCharacterUtilities.cs</Link> </Compile> <Compile Include="..\..\..\..\Compilers\CSharp\Portable\Syntax\SyntaxKind.cs"> <Link>CSharp\Compiler\SyntaxKind.cs</Link> </Compile> <Compile Include="..\..\..\..\Compilers\CSharp\Portable\Syntax\SyntaxKindFacts.cs"> <Link>CSharp\Compiler\SyntaxKindFacts.cs</Link> </Compile> <Compile Include="..\ExpressionCompiler\DkmExceptionUtilities.cs"> <Link>ExpressionCompiler\DkmExceptionUtilities.cs</Link> </Compile> <VsdConfigXmlFiles Include="CSharp\FunctionResolver.vsdconfigxml" /> <VsdConfigXmlFiles Include="VisualBasic\FunctionResolver.vsdconfigxml" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.ExpressionEvaluator.FunctionResolver.UnitTests" /> </ItemGroup> <ItemGroup> <PackageReference Include="System.Collections.Immutable" Version="$(SystemCollectionsImmutableVersion)" /> <PackageReference Include="System.Reflection.Metadata" Version="$(SystemReflectionMetadataVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Debugger.Engine-implementation" Version="$(MicrosoftVisualStudioDebuggerEngineimplementationVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Debugger.Metadata-implementation"> <Version>$(MicrosoftVisualStudioDebuggerMetadataimplementationVersion)</Version> <ExcludeAssets>compile</ExcludeAssets> </PackageReference> <!-- Remove once https://github.com/dotnet/sdk/issues/19506 is resolved --> <PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="$(MicrosoftNETFrameworkReferenceAssembliesVersion)" /> </ItemGroup> <Import Project="$(RepositoryEngineeringDir)targets\Vsdconfig.targets" /> </Project>
1
dotnet/roslyn
55,408
Update package references
CyrusNajmabadi
2021-08-04T19:12:45Z
2021-08-04T22:34:08Z
967cf7cf7be8478cce7cda728217eab8504f2863
d41ae79bb1a3f0deb2de2f3d67c976f795da9563
Update package references.
./src/Workspaces/MSBuildTest/Resources/ProjectFiles/CSharp/PortableProject.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> <PropertyGroup> <MinimumVisualStudioVersion>11.0</MinimumVisualStudioVersion> <Configuration Condition="'$(Configuration)' == ''">Debug</Configuration> <Platform Condition="'$(Platform)' == ''">AnyCPU</Platform> <PlatformTarget>AnyCPU</PlatformTarget> <ProjectGuid>{f4261866-0652-4115-b022-0e4f4e4d903e}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Portly</RootNamespace> <AssemblyName>Portly</AssemblyName> <DefaultLanguage>en-US</DefaultLanguage> <FileAlignment>512</FileAlignment> <ProjectTypeGuids>{786C830F-07A1-408B-BD7F-6EE04809D6DB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids> <TargetFrameworkProfile>Profile259</TargetFrameworkProfile> <TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'"> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'"> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <!-- A reference to the entire .NET Framework is automatically included --> </ItemGroup> <ItemGroup> <Compile Include="CSharpClass.cs" /> </ItemGroup> <Import Project="$(MSBuildExtensionsPath32)\Microsoft\Portable\$(TargetFrameworkVersion)\Microsoft.Portable.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> <PropertyGroup> <MinimumVisualStudioVersion>11.0</MinimumVisualStudioVersion> <Configuration Condition="'$(Configuration)' == ''">Debug</Configuration> <Platform Condition="'$(Platform)' == ''">AnyCPU</Platform> <PlatformTarget>AnyCPU</PlatformTarget> <ProjectGuid>{f4261866-0652-4115-b022-0e4f4e4d903e}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Portly</RootNamespace> <AssemblyName>Portly</AssemblyName> <DefaultLanguage>en-US</DefaultLanguage> <FileAlignment>512</FileAlignment> <ProjectTypeGuids>{786C830F-07A1-408B-BD7F-6EE04809D6DB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids> <TargetFrameworkProfile>Profile259</TargetFrameworkProfile> <TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'"> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'"> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <!-- A reference to the entire .NET Framework is automatically included --> </ItemGroup> <ItemGroup> <Compile Include="CSharpClass.cs" /> </ItemGroup> <Import Project="$(MSBuildExtensionsPath32)\Microsoft\Portable\$(TargetFrameworkVersion)\Microsoft.Portable.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project>
-1
dotnet/roslyn
55,408
Update package references
CyrusNajmabadi
2021-08-04T19:12:45Z
2021-08-04T22:34:08Z
967cf7cf7be8478cce7cda728217eab8504f2863
d41ae79bb1a3f0deb2de2f3d67c976f795da9563
Update package references.
./src/Workspaces/MSBuildTest/Resources/ProjectFiles/CSharp/MallformedAdditionalFilePath.csproj
<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProjectGuid>{CE26EDB5-9F46-46D4-8EC0-9BC9293A8BE8}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>MalformedProject</RootNamespace> <AssemblyName>MalformedProject</AssemblyName> <TargetFrameworkVersion>v4.6</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> <Deterministic>true</Deterministic> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="System" /> <Reference Include="System.Core" /> <Reference Include="Microsoft.CSharp" /> </ItemGroup> <ItemGroup> <Compile Include="Class1.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> </ItemGroup> <ItemGroup> <AdditionalFiles Include="ValidAdditionalFile.txt" /> <AdditionalFiles Include="TEST::" /> <AdditionalFiles Include="COM1" /> </ItemGroup> <ItemGroup /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> </Project>
<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProjectGuid>{CE26EDB5-9F46-46D4-8EC0-9BC9293A8BE8}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>MalformedProject</RootNamespace> <AssemblyName>MalformedProject</AssemblyName> <TargetFrameworkVersion>v4.6</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> <Deterministic>true</Deterministic> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="System" /> <Reference Include="System.Core" /> <Reference Include="Microsoft.CSharp" /> </ItemGroup> <ItemGroup> <Compile Include="Class1.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> </ItemGroup> <ItemGroup> <AdditionalFiles Include="ValidAdditionalFile.txt" /> <AdditionalFiles Include="TEST::" /> <AdditionalFiles Include="COM1" /> </ItemGroup> <ItemGroup /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> </Project>
-1
dotnet/roslyn
55,408
Update package references
CyrusNajmabadi
2021-08-04T19:12:45Z
2021-08-04T22:34:08Z
967cf7cf7be8478cce7cda728217eab8504f2863
d41ae79bb1a3f0deb2de2f3d67c976f795da9563
Update package references.
./src/Workspaces/Core/Desktop/Microsoft.CodeAnalysis.Workspaces.Desktop.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis</RootNamespace> <TargetFrameworks>net472;netcoreapp3.1</TargetFrameworks> <ExcludeFromSourceBuild>true</ExcludeFromSourceBuild> <!-- NuGet --> <IsPackable>true</IsPackable> </PropertyGroup> <ItemGroup> <PackageReference Include="System.ComponentModel.Composition" Version="$(SystemComponentModelCompositionVersion)" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.EditorFeatures" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Features" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.CSharp" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.Implementation" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.Razor.RemoteClient" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.VisualBasic" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Remote.Workspaces" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Remote.Razor.ServiceHub" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Remote.ServiceHub" /> <InternalsVisibleTo Include="Roslyn.Hosting.Diagnostics" /> <InternalsVisibleTo Include="Roslyn.VisualStudio.Setup" /> <InternalsVisibleTo Include="Roslyn.VisualStudio.DiagnosticsWindow" /> <!-- BEGIN MONODEVELOP These MonoDevelop dependencies don't ship with Visual Studio, so can't break our binary insertions and are exempted from the ExternalAccess adapter assembly policies. --> <InternalsVisibleTo Include="MonoDevelop.Ide" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.Refactoring" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.CSharpBinding" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.VBNetBinding" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.Ide.Tests" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.Refactoring.Tests" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.CSharpBinding.Tests" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.VBNetBinding.Tests" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <!-- END MONODEVELOP --> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures2.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities2" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Workspaces.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Workspaces.Desktop.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Workspaces.Test.Utilities" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.Test.Utilities2" /> <InternalsVisibleTo Include="DynamicProxyGenAssembly2" Key="$(MoqPublicKey)" LoadsWithinVisualStudio="false" /> </ItemGroup> <ItemGroup> <PublicAPI Include="PublicAPI.Shipped.txt" /> <PublicAPI Include="PublicAPI.Unshipped.txt" /> </ItemGroup> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis</RootNamespace> <TargetFrameworks>net472;netcoreapp3.1</TargetFrameworks> <ExcludeFromSourceBuild>true</ExcludeFromSourceBuild> <!-- NuGet --> <IsPackable>true</IsPackable> </PropertyGroup> <ItemGroup> <PackageReference Include="System.ComponentModel.Composition" Version="$(SystemComponentModelCompositionVersion)" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.EditorFeatures" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Features" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.CSharp" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.Implementation" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.Razor.RemoteClient" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.VisualBasic" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Remote.Workspaces" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Remote.Razor.ServiceHub" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Remote.ServiceHub" /> <InternalsVisibleTo Include="Roslyn.Hosting.Diagnostics" /> <InternalsVisibleTo Include="Roslyn.VisualStudio.Setup" /> <InternalsVisibleTo Include="Roslyn.VisualStudio.DiagnosticsWindow" /> <!-- BEGIN MONODEVELOP These MonoDevelop dependencies don't ship with Visual Studio, so can't break our binary insertions and are exempted from the ExternalAccess adapter assembly policies. --> <InternalsVisibleTo Include="MonoDevelop.Ide" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.Refactoring" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.CSharpBinding" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.VBNetBinding" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.Ide.Tests" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.Refactoring.Tests" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.CSharpBinding.Tests" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.VBNetBinding.Tests" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <!-- END MONODEVELOP --> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures2.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities2" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Workspaces.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Workspaces.Desktop.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Workspaces.Test.Utilities" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.Test.Utilities2" /> <InternalsVisibleTo Include="DynamicProxyGenAssembly2" Key="$(MoqPublicKey)" LoadsWithinVisualStudio="false" /> </ItemGroup> <ItemGroup> <PublicAPI Include="PublicAPI.Shipped.txt" /> <PublicAPI Include="PublicAPI.Unshipped.txt" /> </ItemGroup> </Project>
-1
dotnet/roslyn
55,408
Update package references
CyrusNajmabadi
2021-08-04T19:12:45Z
2021-08-04T22:34:08Z
967cf7cf7be8478cce7cda728217eab8504f2863
d41ae79bb1a3f0deb2de2f3d67c976f795da9563
Update package references.
./src/Tools/ExternalAccess/Debugger/Microsoft.CodeAnalysis.ExternalAccess.Debugger.csproj
<?xml version="1.0" encoding="utf-8"?> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis.ExternalAccess.Debugger</RootNamespace> <TargetFramework>netstandard2.0</TargetFramework> <!-- NuGet --> <IsPackable>true</IsPackable> <PackageId>Microsoft.CodeAnalysis.ExternalAccess.Debugger</PackageId> <PackageDescription> A supporting package for the Visual Studio debugger: https://devdiv.visualstudio.com/DevDiv/_git/VS?path=%2Fsrc%2Fdebugger%2FRazor </PackageDescription> </PropertyGroup> <ItemGroup> <!-- ⚠ ONLY VISUAL STUDIO DEBUGGER ASSEMBLIES MAY BE ADDED HERE ⚠ --> <InternalsVisibleTo Include="VsDebugPresentationPackage" Key="$(VisualStudioDebuggerKey)" /> </ItemGroup> <ItemGroup> <PackageReference Include="System.Buffers" Version="$(SystemBuffersVersion)" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\..\EditorFeatures\Core\Microsoft.CodeAnalysis.EditorFeatures.csproj" /> <ProjectReference Include="..\..\..\Workspaces\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" /> </ItemGroup> <ItemGroup> <PublicAPI Include="PublicAPI.Shipped.txt" /> <PublicAPI Include="PublicAPI.Unshipped.txt" /> </ItemGroup> </Project>
<?xml version="1.0" encoding="utf-8"?> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis.ExternalAccess.Debugger</RootNamespace> <TargetFramework>netstandard2.0</TargetFramework> <!-- NuGet --> <IsPackable>true</IsPackable> <PackageId>Microsoft.CodeAnalysis.ExternalAccess.Debugger</PackageId> <PackageDescription> A supporting package for the Visual Studio debugger: https://devdiv.visualstudio.com/DevDiv/_git/VS?path=%2Fsrc%2Fdebugger%2FRazor </PackageDescription> </PropertyGroup> <ItemGroup> <!-- ⚠ ONLY VISUAL STUDIO DEBUGGER ASSEMBLIES MAY BE ADDED HERE ⚠ --> <InternalsVisibleTo Include="VsDebugPresentationPackage" Key="$(VisualStudioDebuggerKey)" /> </ItemGroup> <ItemGroup> <PackageReference Include="System.Buffers" Version="$(SystemBuffersVersion)" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\..\EditorFeatures\Core\Microsoft.CodeAnalysis.EditorFeatures.csproj" /> <ProjectReference Include="..\..\..\Workspaces\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" /> </ItemGroup> <ItemGroup> <PublicAPI Include="PublicAPI.Shipped.txt" /> <PublicAPI Include="PublicAPI.Unshipped.txt" /> </ItemGroup> </Project>
-1
dotnet/roslyn
55,408
Update package references
CyrusNajmabadi
2021-08-04T19:12:45Z
2021-08-04T22:34:08Z
967cf7cf7be8478cce7cda728217eab8504f2863
d41ae79bb1a3f0deb2de2f3d67c976f795da9563
Update package references.
./src/Workspaces/MSBuildTest/Resources/ProjectFiles/CSharp/BadTasks.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition="'$(Configuration)' == ''">Debug</Configuration> <Platform Condition="'$(Platform)' == ''">AnyCPU</Platform> <PlatformTarget>AnyCPU</PlatformTarget> <ProductVersion>8.0.30703</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{686DD036-86AA-443E-8A10-DDB43266A8C4}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>CSharpProject</RootNamespace> <AssemblyName>CSharpProject</AssemblyName> <TargetFrameworkVersion>v4.6</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> <AssemblyOriginatorKeyFile>snKey.snk</AssemblyOriginatorKeyFile> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'"> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'"> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="Microsoft.CSharp" /> <Reference Include="System" /> <Reference Include="System.Core" /> </ItemGroup> <ItemGroup> <Compile Include="CSharpClass.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharpie.targets" /> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition="'$(Configuration)' == ''">Debug</Configuration> <Platform Condition="'$(Platform)' == ''">AnyCPU</Platform> <PlatformTarget>AnyCPU</PlatformTarget> <ProductVersion>8.0.30703</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{686DD036-86AA-443E-8A10-DDB43266A8C4}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>CSharpProject</RootNamespace> <AssemblyName>CSharpProject</AssemblyName> <TargetFrameworkVersion>v4.6</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> <AssemblyOriginatorKeyFile>snKey.snk</AssemblyOriginatorKeyFile> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'"> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'"> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="Microsoft.CSharp" /> <Reference Include="System" /> <Reference Include="System.Core" /> </ItemGroup> <ItemGroup> <Compile Include="CSharpClass.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharpie.targets" /> </Project>
-1
dotnet/roslyn
55,408
Update package references
CyrusNajmabadi
2021-08-04T19:12:45Z
2021-08-04T22:34:08Z
967cf7cf7be8478cce7cda728217eab8504f2863
d41ae79bb1a3f0deb2de2f3d67c976f795da9563
Update package references.
./src/Workspaces/MSBuildTest/Resources/Issue30174/ReferencedLibrary/ReferencedLibrary.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> </PropertyGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> </PropertyGroup> </Project>
-1
dotnet/roslyn
55,408
Update package references
CyrusNajmabadi
2021-08-04T19:12:45Z
2021-08-04T22:34:08Z
967cf7cf7be8478cce7cda728217eab8504f2863
d41ae79bb1a3f0deb2de2f3d67c976f795da9563
Update package references.
./src/Test/PdbUtilities/Roslyn.Test.PdbUtilities.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Roslyn.Test.PdbUtilities</RootNamespace> <TargetFrameworks>netcoreapp3.1;net472</TargetFrameworks> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <IsShipping>false</IsShipping> </PropertyGroup> <ItemGroup> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.CommandLine.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.Emit.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.WinRT.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.Symbol.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.Syntax.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.Test.Utilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.CommandLine.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Emit.UnitTests" /> <InternalsVisibleTo Include="Roslyn.Compilers.VisualBasic.IOperation.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Semantic.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Symbol.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Syntax.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Test.Utilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.ExpressionCompiler.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.ResultProvider.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.Utilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.ExpressionEvaluator.FunctionResolver.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.ExpressionCompiler.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.ResultProvider.UnitTests" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.DiaSymReader" Version="$(MicrosoftDiaSymReaderVersion)" Aliases="DSR"/> <PackageReference Include="Microsoft.DiaSymReader.PortablePdb" Version="$(MicrosoftDiaSymReaderPortablePdbVersion)" /> <PackageReference Include="Microsoft.DiaSymReader.Converter" Version="$(MicrosoftDiaSymReaderConverterVersion)" /> <PackageReference Include="Microsoft.DiaSymReader.Converter.Xml" Version="$(MicrosoftDiaSymReaderConverterXmlVersion)" /> <PackageReference Include="Microsoft.Metadata.Visualizer" Version="$(MicrosoftMetadataVisualizerVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="$(SystemCollectionsImmutableVersion)" /> <PackageReference Include="System.Reflection.Metadata" Version="$(SystemReflectionMetadataVersion)" /> <PackageReference Include="xunit.assert" Version="$(xunitassertVersion)" /> </ItemGroup> <ItemGroup> <!-- Package references needed due to Microsoft.DiaSymReader.Converter dependency on Newtonsoft.Json 9.0.1, which doesn't have netstandard 2.0 binaries. --> <PackageReference Include="System.IO.FileSystem" Version="$(SystemIOFileSystemVersion)" /> <PackageReference Include="System.IO.FileSystem.Primitives" Version="$(SystemIOFileSystemPrimitivesVersion)" /> <PackageReference Include="System.Text.Encoding.Extensions" Version="$(SystemTextEncodingExtensionsVersion)" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" /> </ItemGroup> <Import Project="$(RepositoryEngineeringDir)targets\DiaSymReaderNative.targets" /> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Roslyn.Test.PdbUtilities</RootNamespace> <TargetFrameworks>netcoreapp3.1;net472</TargetFrameworks> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <IsShipping>false</IsShipping> </PropertyGroup> <ItemGroup> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.CommandLine.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.Emit.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.WinRT.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.Symbol.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.Syntax.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.Test.Utilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.CommandLine.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Emit.UnitTests" /> <InternalsVisibleTo Include="Roslyn.Compilers.VisualBasic.IOperation.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Semantic.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Symbol.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Syntax.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Test.Utilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.ExpressionCompiler.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.ResultProvider.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.Utilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.ExpressionEvaluator.FunctionResolver.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.ExpressionCompiler.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.ResultProvider.UnitTests" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.DiaSymReader" Version="$(MicrosoftDiaSymReaderVersion)" Aliases="DSR"/> <PackageReference Include="Microsoft.DiaSymReader.PortablePdb" Version="$(MicrosoftDiaSymReaderPortablePdbVersion)" /> <PackageReference Include="Microsoft.DiaSymReader.Converter" Version="$(MicrosoftDiaSymReaderConverterVersion)" /> <PackageReference Include="Microsoft.DiaSymReader.Converter.Xml" Version="$(MicrosoftDiaSymReaderConverterXmlVersion)" /> <PackageReference Include="Microsoft.Metadata.Visualizer" Version="$(MicrosoftMetadataVisualizerVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="$(SystemCollectionsImmutableVersion)" /> <PackageReference Include="System.Reflection.Metadata" Version="$(SystemReflectionMetadataVersion)" /> <PackageReference Include="xunit.assert" Version="$(xunitassertVersion)" /> </ItemGroup> <ItemGroup> <!-- Package references needed due to Microsoft.DiaSymReader.Converter dependency on Newtonsoft.Json 9.0.1, which doesn't have netstandard 2.0 binaries. --> <PackageReference Include="System.IO.FileSystem" Version="$(SystemIOFileSystemVersion)" /> <PackageReference Include="System.IO.FileSystem.Primitives" Version="$(SystemIOFileSystemPrimitivesVersion)" /> <PackageReference Include="System.Text.Encoding.Extensions" Version="$(SystemTextEncodingExtensionsVersion)" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" /> </ItemGroup> <Import Project="$(RepositoryEngineeringDir)targets\DiaSymReaderNative.targets" /> </Project>
-1
dotnet/roslyn
55,408
Update package references
CyrusNajmabadi
2021-08-04T19:12:45Z
2021-08-04T22:34:08Z
967cf7cf7be8478cce7cda728217eab8504f2863
d41ae79bb1a3f0deb2de2f3d67c976f795da9563
Update package references.
./src/Tools/ExternalAccess/Xamarin.Remote/Microsoft.CodeAnalysis.ExternalAccess.Xamarin.Remote.csproj
<?xml version="1.0" encoding="utf-8"?> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis.ExternalAccess.Xamarin.Remote</RootNamespace> <TargetFramework>net472</TargetFramework> <!-- NuGet --> <IsPackable>true</IsPackable> <PackageId>Microsoft.CodeAnalysis.ExternalAccess.Xamarin.Remote</PackageId> <PackageDescription> A supporting package for Xamarin: https://github.com/xamarin/CodeAnalysis </PackageDescription> </PropertyGroup> <ItemGroup> <!-- ⚠ ONLY XAMARIN ASSEMBLIES MAY BE ADDED HERE ⚠ --> <InternalsVisibleTo Include="Xamarin.CodeAnalysis.Remote" Key="$(XamarinKey)" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.VisualStudio.CoreUtility" Version="$(MicrosoftVisualStudioCoreUtilityVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Imaging" Version="$(MicrosoftVisualStudioImagingVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Imaging.Interop.14.0.DesignTime" Version="$(MicrosoftVisualStudioImagingInterop140DesignTimeVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Text.Data" Version="$(MicrosoftVisualStudioTextDataVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Text.Logic" Version="$(MicrosoftVisualStudioTextLogicVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Text.UI" Version="$(MicrosoftVisualStudioTextUIVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Threading" Version="$(MicrosoftVisualStudioThreadingVersion)" /> <PackageReference Include="StreamJsonRpc" Version="$(StreamJsonRpcVersion)" /> <PackageReference Include="Newtonsoft.Json" Version="$(NewtonsoftJsonVersion)" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\..\Workspaces\Remote\ServiceHub\Microsoft.CodeAnalysis.Remote.ServiceHub.csproj" /> </ItemGroup> <ItemGroup> <PublicAPI Include="PublicAPI.Shipped.txt" /> <PublicAPI Include="PublicAPI.Unshipped.txt" /> </ItemGroup> </Project>
<?xml version="1.0" encoding="utf-8"?> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis.ExternalAccess.Xamarin.Remote</RootNamespace> <TargetFramework>net472</TargetFramework> <!-- NuGet --> <IsPackable>true</IsPackable> <PackageId>Microsoft.CodeAnalysis.ExternalAccess.Xamarin.Remote</PackageId> <PackageDescription> A supporting package for Xamarin: https://github.com/xamarin/CodeAnalysis </PackageDescription> </PropertyGroup> <ItemGroup> <!-- ⚠ ONLY XAMARIN ASSEMBLIES MAY BE ADDED HERE ⚠ --> <InternalsVisibleTo Include="Xamarin.CodeAnalysis.Remote" Key="$(XamarinKey)" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.VisualStudio.CoreUtility" Version="$(MicrosoftVisualStudioCoreUtilityVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Imaging" Version="$(MicrosoftVisualStudioImagingVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Imaging.Interop.14.0.DesignTime" Version="$(MicrosoftVisualStudioImagingInterop140DesignTimeVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Text.Data" Version="$(MicrosoftVisualStudioTextDataVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Text.Logic" Version="$(MicrosoftVisualStudioTextLogicVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Text.UI" Version="$(MicrosoftVisualStudioTextUIVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Threading" Version="$(MicrosoftVisualStudioThreadingVersion)" /> <PackageReference Include="StreamJsonRpc" Version="$(StreamJsonRpcVersion)" /> <PackageReference Include="Newtonsoft.Json" Version="$(NewtonsoftJsonVersion)" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\..\Workspaces\Remote\ServiceHub\Microsoft.CodeAnalysis.Remote.ServiceHub.csproj" /> </ItemGroup> <ItemGroup> <PublicAPI Include="PublicAPI.Shipped.txt" /> <PublicAPI Include="PublicAPI.Unshipped.txt" /> </ItemGroup> </Project>
-1
dotnet/roslyn
55,408
Update package references
CyrusNajmabadi
2021-08-04T19:12:45Z
2021-08-04T22:34:08Z
967cf7cf7be8478cce7cda728217eab8504f2863
d41ae79bb1a3f0deb2de2f3d67c976f795da9563
Update package references.
./src/Tools/ExternalAccess/FSharp/Microsoft.CodeAnalysis.ExternalAccess.FSharp.csproj
<?xml version="1.0" encoding="utf-8"?> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis.ExternalAccess.FSharp</RootNamespace> <TargetFramework>net472</TargetFramework> <!-- NuGet --> <IsPackable>true</IsPackable> <PackageId>Microsoft.CodeAnalysis.ExternalAccess.FSharp</PackageId> <PackageDescription> A supporting package for F#: https://github.com/Microsoft/visualfsharp </PackageDescription> </PropertyGroup> <ItemGroup> <!-- ⚠ ONLY F# ASSEMBLIES MAY BE ADDED HERE ⚠ --> <InternalsVisibleTo Include="FSharp.Editor" Key="$(FSharpKey)" /> <InternalsVisibleTo Include="FSharp.LanguageService" Key="$(FSharpKey)" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.ExternalAccess.FSharp.UnitTests" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\..\EditorFeatures\Core\Microsoft.CodeAnalysis.EditorFeatures.csproj" /> <ProjectReference Include="..\..\..\Features\Core\Portable\Microsoft.CodeAnalysis.Features.csproj" /> <ProjectReference Include="..\..\..\VisualStudio\Core\Def\Microsoft.VisualStudio.LanguageServices.csproj" /> <ProjectReference Include="..\..\..\EditorFeatures\CSharp\Microsoft.CodeAnalysis.CSharp.EditorFeatures.csproj" /> <ProjectReference Include="..\..\..\Workspaces\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" /> <ProjectReference Include="..\..\..\EditorFeatures\Core.Wpf\Microsoft.CodeAnalysis.EditorFeatures.Wpf.csproj" /> </ItemGroup> <ItemGroup> <PublicAPI Include="PublicAPI.Shipped.txt" /> <PublicAPI Include="PublicAPI.Unshipped.txt" /> </ItemGroup> <ItemGroup> <Reference Include="System.ComponentModel.Composition" /> </ItemGroup> <ItemGroup> <Compile Update="ExternalAccessFSharpResources.Designer.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <DependentUpon>ExternalAccessFSharpResources.resx</DependentUpon> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="ExternalAccessFSharpResources.resx"> <Generator>ResXFileCodeGenerator</Generator> <LastGenOutput>ExternalAccessFSharpResources.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> </Project>
<?xml version="1.0" encoding="utf-8"?> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis.ExternalAccess.FSharp</RootNamespace> <TargetFramework>net472</TargetFramework> <!-- NuGet --> <IsPackable>true</IsPackable> <PackageId>Microsoft.CodeAnalysis.ExternalAccess.FSharp</PackageId> <PackageDescription> A supporting package for F#: https://github.com/Microsoft/visualfsharp </PackageDescription> </PropertyGroup> <ItemGroup> <!-- ⚠ ONLY F# ASSEMBLIES MAY BE ADDED HERE ⚠ --> <InternalsVisibleTo Include="FSharp.Editor" Key="$(FSharpKey)" /> <InternalsVisibleTo Include="FSharp.LanguageService" Key="$(FSharpKey)" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.ExternalAccess.FSharp.UnitTests" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\..\EditorFeatures\Core\Microsoft.CodeAnalysis.EditorFeatures.csproj" /> <ProjectReference Include="..\..\..\Features\Core\Portable\Microsoft.CodeAnalysis.Features.csproj" /> <ProjectReference Include="..\..\..\VisualStudio\Core\Def\Microsoft.VisualStudio.LanguageServices.csproj" /> <ProjectReference Include="..\..\..\EditorFeatures\CSharp\Microsoft.CodeAnalysis.CSharp.EditorFeatures.csproj" /> <ProjectReference Include="..\..\..\Workspaces\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" /> <ProjectReference Include="..\..\..\EditorFeatures\Core.Wpf\Microsoft.CodeAnalysis.EditorFeatures.Wpf.csproj" /> </ItemGroup> <ItemGroup> <PublicAPI Include="PublicAPI.Shipped.txt" /> <PublicAPI Include="PublicAPI.Unshipped.txt" /> </ItemGroup> <ItemGroup> <Reference Include="System.ComponentModel.Composition" /> </ItemGroup> <ItemGroup> <Compile Update="ExternalAccessFSharpResources.Designer.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <DependentUpon>ExternalAccessFSharpResources.resx</DependentUpon> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="ExternalAccessFSharpResources.resx"> <Generator>ResXFileCodeGenerator</Generator> <LastGenOutput>ExternalAccessFSharpResources.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> </Project>
-1
dotnet/roslyn
55,408
Update package references
CyrusNajmabadi
2021-08-04T19:12:45Z
2021-08-04T22:34:08Z
967cf7cf7be8478cce7cda728217eab8504f2863
d41ae79bb1a3f0deb2de2f3d67c976f795da9563
Update package references.
./src/Workspaces/DesktopTest/Microsoft.CodeAnalysis.Workspaces.Desktop.UnitTests.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk.WindowsDesktop"> <PropertyGroup> <OutputType>Library</OutputType> <TargetFramework>net472</TargetFramework> <UseWpf>true</UseWpf> <RootNamespace>Microsoft.CodeAnalysis.UnitTests</RootNamespace> </PropertyGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" /> <ProjectReference Include="..\CoreTestUtilities\Microsoft.CodeAnalysis.Workspaces.Test.Utilities.csproj" /> <ProjectReference Include="..\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Workspaces.csproj" /> <ProjectReference Include="..\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Workspaces.vbproj" /> <ProjectReference Include="..\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" /> <ProjectReference Include="..\Core\Desktop\Microsoft.CodeAnalysis.Workspaces.Desktop.csproj" /> <ProjectReference Include="..\..\Compilers\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" /> <ProjectReference Include="..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" /> <ProjectReference Include="..\..\Features\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Features.csproj" /> <ProjectReference Include="..\..\EditorFeatures\Core\Microsoft.CodeAnalysis.EditorFeatures.csproj" /> <ProjectReference Include="..\..\EditorFeatures\Text\Microsoft.CodeAnalysis.EditorFeatures.Text.csproj" /> <ProjectReference Include="..\..\Features\Core\Portable\Microsoft.CodeAnalysis.Features.csproj" /> <ProjectReference Include="..\..\Scripting\Core\Microsoft.CodeAnalysis.Scripting.csproj" /> <ProjectReference Include="..\Remote\Core\Microsoft.CodeAnalysis.Remote.Workspaces.csproj" /> <ProjectReference Include="..\..\Features\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Features.vbproj" /> <ProjectReference Include="..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.CSharp" Version="$(MicrosoftCSharpVersion)" /> </ItemGroup> <ItemGroup> <Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" /> </ItemGroup> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk.WindowsDesktop"> <PropertyGroup> <OutputType>Library</OutputType> <TargetFramework>net472</TargetFramework> <UseWpf>true</UseWpf> <RootNamespace>Microsoft.CodeAnalysis.UnitTests</RootNamespace> </PropertyGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" /> <ProjectReference Include="..\CoreTestUtilities\Microsoft.CodeAnalysis.Workspaces.Test.Utilities.csproj" /> <ProjectReference Include="..\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Workspaces.csproj" /> <ProjectReference Include="..\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Workspaces.vbproj" /> <ProjectReference Include="..\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" /> <ProjectReference Include="..\Core\Desktop\Microsoft.CodeAnalysis.Workspaces.Desktop.csproj" /> <ProjectReference Include="..\..\Compilers\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" /> <ProjectReference Include="..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" /> <ProjectReference Include="..\..\Features\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Features.csproj" /> <ProjectReference Include="..\..\EditorFeatures\Core\Microsoft.CodeAnalysis.EditorFeatures.csproj" /> <ProjectReference Include="..\..\EditorFeatures\Text\Microsoft.CodeAnalysis.EditorFeatures.Text.csproj" /> <ProjectReference Include="..\..\Features\Core\Portable\Microsoft.CodeAnalysis.Features.csproj" /> <ProjectReference Include="..\..\Scripting\Core\Microsoft.CodeAnalysis.Scripting.csproj" /> <ProjectReference Include="..\Remote\Core\Microsoft.CodeAnalysis.Remote.Workspaces.csproj" /> <ProjectReference Include="..\..\Features\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Features.vbproj" /> <ProjectReference Include="..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.CSharp" Version="$(MicrosoftCSharpVersion)" /> </ItemGroup> <ItemGroup> <Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" /> </ItemGroup> </Project>
-1
dotnet/roslyn
55,408
Update package references
CyrusNajmabadi
2021-08-04T19:12:45Z
2021-08-04T22:34:08Z
967cf7cf7be8478cce7cda728217eab8504f2863
d41ae79bb1a3f0deb2de2f3d67c976f795da9563
Update package references.
./src/Features/Core/Portable/Microsoft.CodeAnalysis.Features.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis</RootNamespace> <TargetFrameworks>netcoreapp3.1;netstandard2.0</TargetFrameworks> <ApplyNgenOptimization>partial</ApplyNgenOptimization> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <!-- NuGet --> <IsPackable>true</IsPackable> <PackageDescription> .NET Compiler Platform ("Roslyn") support for creating editing experiences. </PackageDescription> </PropertyGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\..\Workspaces\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" /> <ProjectReference Include="..\..\..\Scripting\Core\Microsoft.CodeAnalysis.Scripting.csproj" Aliases="Scripting,global" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.EditorFeatures" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.Features" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Text" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Wpf" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.InteractiveEditorFeatures" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.InteractiveFeatures" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.LanguageServer.Protocol" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.LanguageServer.Protocol.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.ExternalAccess.UnitTesting" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.CodeLens" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.CSharp" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.Implementation" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.LiveShare" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.LiveShare.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.ExternalDependencyServices" WorkItem="https://github.com/dotnet/roslyn/issues/35085" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.VisualBasic" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.Xaml" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Remote.ServiceHub" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Remote.Workspaces" /> <RestrictedInternalsVisibleTo Include="Microsoft.CodeAnalysis.LiveUnitTesting.Orchestrator" Partner="UnitTesting" Key="$(UnitTestingKey)" /> <RestrictedInternalsVisibleTo Include="Microsoft.CodeAnalysis.UnitTesting.SourceBasedTestDiscovery" Partner="UnitTesting" Key="$(UnitTestingKey)" /> <RestrictedInternalsVisibleTo Include="Microsoft.CodeAnalysis.UnitTesting.SourceBasedTestDiscovery.Core" Partner="UnitTesting" Key="$(UnitTestingKey)" /> <RestrictedInternalsVisibleTo Include="Microsoft.VisualStudio.TestWindow.Core" Partner="UnitTesting" Key="$(UnitTestingKey)" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.EditorFeatures" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Features" /> <InternalsVisibleTo Include="Roslyn.Hosting.Diagnostics" /> <InternalsVisibleTo Include="Roslyn.VisualStudio.DiagnosticsWindow" /> <InternalsVisibleTo Include="Roslyn.VisualStudio.Setup" /> <InternalsVisibleTo Include="VBCSCompiler" /> <InternalsVisibleTo Include="AnalyzerRunner" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures2.UnitTests" /> <!-- BEGIN MONODEVELOP These MonoDevelop dependencies don't ship with Visual Studio, so can't break our binary insertions and are exempted from the ExternalAccess adapter assembly policies. --> <InternalsVisibleTo Include="MonoDevelop.Ide" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.Refactoring" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.CSharpBinding" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.VBNetBinding" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.Ide.Tests" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.Refactoring.Tests" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.CSharpBinding.Tests" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.VBNetBinding.Tests" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <!-- this is currently built externally, as part of the MonoDevelop build --> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Cocoa" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Cocoa.UnitTests" LoadsWithinVisualStudio="false" /> <!-- END MONODEVELOP --> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.EditorFeatures2.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures2.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Workspaces.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.IntegrationTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.IntegrationTest.Utilities" /> <InternalsVisibleTo Include="Roslyn.VisualStudio.Next.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.DiagnosticsTests.Utilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CodeStyle.LegacyTestFramework.UnitTestUtilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities2" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.Test.Utilities2" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.ExternalAccess.FSharp" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.ExternalAccess.FSharp.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.ExternalAccess.OmniSharp" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.CSharp" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.TypeScript.EditorFeatures" Key="$(TypeScriptKey)" WorkItem="https://github.com/dotnet/roslyn/issues/35077" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.TypeScript" Key="$(TypeScriptKey)" WorkItem="https://github.com/dotnet/roslyn/issues/35077" /> <InternalsVisibleTo Include="Roslyn.Services.Editor.TypeScript.UnitTests" Key="$(TypeScriptKey)" WorkItem="https://github.com/dotnet/roslyn/issues/35077" /> <InternalsVisibleTo Include="DynamicProxyGenAssembly2" Key="$(MoqPublicKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="Microsoft.Test.Apex.VisualStudio" Key="$(VisualStudioKey)" WorkItem="https://github.com/dotnet/roslyn/issues/35081" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.Alm.Shared.CodeAnalysisClient" Key="$(VisualStudioKey)" WorkItem="https://github.com/dotnet/roslyn/issues/35086" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.CodeSense.Roslyn" Key="$(VisualStudioKey)" WorkItem="https://github.com/dotnet/roslyn/issues/35086" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.CodeSense.ReferencesProvider" Key="$(VisualStudioKey)" WorkItem="https://github.com/dotnet/roslyn/issues/35086" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.CodeSense.TestsProvider" Key="$(VisualStudioKey)" WorkItem="https://github.com/dotnet/roslyn/issues/35086" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.Completion.Tests" Key="$(IntelliCodeCSharpKey)" WorkItem="https://github.com/dotnet/roslyn/issues/35081" /> <RestrictedInternalsVisibleTo Include="Microsoft.VisualStudio.IntelliCode" Partner="IntelliCode" Key="$(IntelliCodeKey)" /> <RestrictedInternalsVisibleTo Include="Microsoft.VisualStudio.IntelliCode.CSharp" Partner="Pythia" Key="$(IntelliCodeCSharpKey)" /> <RestrictedInternalsVisibleTo Include="Microsoft.VisualStudio.IntelliCode.CSharp.Extraction" Partner="Pythia" Key="$(IntelliCodeCSharpKey)" /> <RestrictedInternalsVisibleTo Include="dotnet-watch" Partner="Watch" Key="$(AspNetCoreKey)" /> <RestrictedInternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServerClient.Razor" Partner="Razor" Key="$(RazorKey)" /> <RestrictedInternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServerClient.Razor.Test" Partner="Razor" Key="$(RazorKey)" /> <InternalsVisibleTo Include="IdeCoreBenchmarks" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.ExternalAccess.Razor" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.ExternalAccess.Razor.UnitTests" /> </ItemGroup> <ItemGroup> <Compile Include="..\..\..\CodeStyle\Core\Analyzers\FormattingAnalyzerHelper.cs" Link="Formatting\FormattingAnalyzerHelper.cs" /> <Compile Include="..\..\..\CodeStyle\Core\CodeFixes\FormattingCodeFixHelper.cs" Link="Formatting\FormattingCodeFixHelper.cs" /> <Compile Include="..\..\..\Compilers\Core\Portable\Text\TextUtilities.cs" Link="Shared\Utilities\TextUtilities.cs" /> <Compile Include="..\..\..\Compilers\Core\Portable\Debugging\SourceHashAlgorithms.cs" Link="Debugging\SourceHashAlgorithms.cs" /> </ItemGroup> <ItemGroup> <EmbeddedResource Update="FeaturesResources.resx" GenerateSource="true" /> </ItemGroup> <ItemGroup> <PublicAPI Include="PublicAPI.Shipped.txt" /> <PublicAPI Include="PublicAPI.Unshipped.txt" /> </ItemGroup> <ItemGroup> <PackageReference Include="System.Threading.Tasks.Extensions" Version="$(SystemThreadingTasksExtensionsVersion)" /> <PackageReference Include="Microsoft.DiaSymReader" Version="$(MicrosoftDiaSymReaderVersion)" /> <PackageReference Include="Microsoft.CodeAnalysis.AnalyzerUtilities" Version="$(MicrosoftCodeAnalysisAnalyzerUtilitiesVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Debugger.Contracts" Version="$(MicrosoftVisualStudioDebuggerContractsVersion)" /> </ItemGroup> <Import Project="..\..\..\Compilers\Core\AnalyzerDriver\AnalyzerDriver.projitems" Label="Shared" /> <Import Project="..\..\..\Dependencies\CodeAnalysis.Debugging\Microsoft.CodeAnalysis.Debugging.projitems" Label="Shared" /> <Import Project="..\..\..\Analyzers\Core\Analyzers\Analyzers.projitems" Label="Shared" /> <Import Project="..\..\..\Analyzers\Core\CodeFixes\CodeFixes.projitems" Label="Shared" /> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis</RootNamespace> <TargetFrameworks>netcoreapp3.1;netstandard2.0</TargetFrameworks> <ApplyNgenOptimization>partial</ApplyNgenOptimization> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <!-- NuGet --> <IsPackable>true</IsPackable> <PackageDescription> .NET Compiler Platform ("Roslyn") support for creating editing experiences. </PackageDescription> </PropertyGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\..\Workspaces\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" /> <ProjectReference Include="..\..\..\Scripting\Core\Microsoft.CodeAnalysis.Scripting.csproj" Aliases="Scripting,global" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.EditorFeatures" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.Features" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Text" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Wpf" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.InteractiveEditorFeatures" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.InteractiveFeatures" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.LanguageServer.Protocol" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.LanguageServer.Protocol.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.ExternalAccess.UnitTesting" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.CodeLens" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.CSharp" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.Implementation" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.LiveShare" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.LiveShare.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.ExternalDependencyServices" WorkItem="https://github.com/dotnet/roslyn/issues/35085" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.VisualBasic" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.Xaml" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Remote.ServiceHub" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Remote.Workspaces" /> <RestrictedInternalsVisibleTo Include="Microsoft.CodeAnalysis.LiveUnitTesting.Orchestrator" Partner="UnitTesting" Key="$(UnitTestingKey)" /> <RestrictedInternalsVisibleTo Include="Microsoft.CodeAnalysis.UnitTesting.SourceBasedTestDiscovery" Partner="UnitTesting" Key="$(UnitTestingKey)" /> <RestrictedInternalsVisibleTo Include="Microsoft.CodeAnalysis.UnitTesting.SourceBasedTestDiscovery.Core" Partner="UnitTesting" Key="$(UnitTestingKey)" /> <RestrictedInternalsVisibleTo Include="Microsoft.VisualStudio.TestWindow.Core" Partner="UnitTesting" Key="$(UnitTestingKey)" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.EditorFeatures" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Features" /> <InternalsVisibleTo Include="Roslyn.Hosting.Diagnostics" /> <InternalsVisibleTo Include="Roslyn.VisualStudio.DiagnosticsWindow" /> <InternalsVisibleTo Include="Roslyn.VisualStudio.Setup" /> <InternalsVisibleTo Include="VBCSCompiler" /> <InternalsVisibleTo Include="AnalyzerRunner" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures2.UnitTests" /> <!-- BEGIN MONODEVELOP These MonoDevelop dependencies don't ship with Visual Studio, so can't break our binary insertions and are exempted from the ExternalAccess adapter assembly policies. --> <InternalsVisibleTo Include="MonoDevelop.Ide" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.Refactoring" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.CSharpBinding" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.VBNetBinding" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.Ide.Tests" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.Refactoring.Tests" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.CSharpBinding.Tests" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.VBNetBinding.Tests" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <!-- this is currently built externally, as part of the MonoDevelop build --> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Cocoa" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Cocoa.UnitTests" LoadsWithinVisualStudio="false" /> <!-- END MONODEVELOP --> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.EditorFeatures2.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures2.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Workspaces.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.IntegrationTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.IntegrationTest.Utilities" /> <InternalsVisibleTo Include="Roslyn.VisualStudio.Next.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.DiagnosticsTests.Utilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CodeStyle.LegacyTestFramework.UnitTestUtilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities2" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.Test.Utilities2" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.ExternalAccess.FSharp" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.ExternalAccess.FSharp.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.ExternalAccess.OmniSharp" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.CSharp" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.TypeScript.EditorFeatures" Key="$(TypeScriptKey)" WorkItem="https://github.com/dotnet/roslyn/issues/35077" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.TypeScript" Key="$(TypeScriptKey)" WorkItem="https://github.com/dotnet/roslyn/issues/35077" /> <InternalsVisibleTo Include="Roslyn.Services.Editor.TypeScript.UnitTests" Key="$(TypeScriptKey)" WorkItem="https://github.com/dotnet/roslyn/issues/35077" /> <InternalsVisibleTo Include="DynamicProxyGenAssembly2" Key="$(MoqPublicKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="Microsoft.Test.Apex.VisualStudio" Key="$(VisualStudioKey)" WorkItem="https://github.com/dotnet/roslyn/issues/35081" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.Alm.Shared.CodeAnalysisClient" Key="$(VisualStudioKey)" WorkItem="https://github.com/dotnet/roslyn/issues/35086" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.CodeSense.Roslyn" Key="$(VisualStudioKey)" WorkItem="https://github.com/dotnet/roslyn/issues/35086" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.CodeSense.ReferencesProvider" Key="$(VisualStudioKey)" WorkItem="https://github.com/dotnet/roslyn/issues/35086" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.CodeSense.TestsProvider" Key="$(VisualStudioKey)" WorkItem="https://github.com/dotnet/roslyn/issues/35086" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.Completion.Tests" Key="$(IntelliCodeCSharpKey)" WorkItem="https://github.com/dotnet/roslyn/issues/35081" /> <RestrictedInternalsVisibleTo Include="Microsoft.VisualStudio.IntelliCode" Partner="IntelliCode" Key="$(IntelliCodeKey)" /> <RestrictedInternalsVisibleTo Include="Microsoft.VisualStudio.IntelliCode.CSharp" Partner="Pythia" Key="$(IntelliCodeCSharpKey)" /> <RestrictedInternalsVisibleTo Include="Microsoft.VisualStudio.IntelliCode.CSharp.Extraction" Partner="Pythia" Key="$(IntelliCodeCSharpKey)" /> <RestrictedInternalsVisibleTo Include="dotnet-watch" Partner="Watch" Key="$(AspNetCoreKey)" /> <RestrictedInternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServerClient.Razor" Partner="Razor" Key="$(RazorKey)" /> <RestrictedInternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServerClient.Razor.Test" Partner="Razor" Key="$(RazorKey)" /> <InternalsVisibleTo Include="IdeCoreBenchmarks" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.ExternalAccess.Razor" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.ExternalAccess.Razor.UnitTests" /> </ItemGroup> <ItemGroup> <Compile Include="..\..\..\CodeStyle\Core\Analyzers\FormattingAnalyzerHelper.cs" Link="Formatting\FormattingAnalyzerHelper.cs" /> <Compile Include="..\..\..\CodeStyle\Core\CodeFixes\FormattingCodeFixHelper.cs" Link="Formatting\FormattingCodeFixHelper.cs" /> <Compile Include="..\..\..\Compilers\Core\Portable\Text\TextUtilities.cs" Link="Shared\Utilities\TextUtilities.cs" /> <Compile Include="..\..\..\Compilers\Core\Portable\Debugging\SourceHashAlgorithms.cs" Link="Debugging\SourceHashAlgorithms.cs" /> </ItemGroup> <ItemGroup> <EmbeddedResource Update="FeaturesResources.resx" GenerateSource="true" /> </ItemGroup> <ItemGroup> <PublicAPI Include="PublicAPI.Shipped.txt" /> <PublicAPI Include="PublicAPI.Unshipped.txt" /> </ItemGroup> <ItemGroup> <PackageReference Include="System.Threading.Tasks.Extensions" Version="$(SystemThreadingTasksExtensionsVersion)" /> <PackageReference Include="Microsoft.DiaSymReader" Version="$(MicrosoftDiaSymReaderVersion)" /> <PackageReference Include="Microsoft.CodeAnalysis.AnalyzerUtilities" Version="$(MicrosoftCodeAnalysisAnalyzerUtilitiesVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Debugger.Contracts" Version="$(MicrosoftVisualStudioDebuggerContractsVersion)" /> </ItemGroup> <Import Project="..\..\..\Compilers\Core\AnalyzerDriver\AnalyzerDriver.projitems" Label="Shared" /> <Import Project="..\..\..\Dependencies\CodeAnalysis.Debugging\Microsoft.CodeAnalysis.Debugging.projitems" Label="Shared" /> <Import Project="..\..\..\Analyzers\Core\Analyzers\Analyzers.projitems" Label="Shared" /> <Import Project="..\..\..\Analyzers\Core\CodeFixes\CodeFixes.projitems" Label="Shared" /> </Project>
-1
dotnet/roslyn
55,408
Update package references
CyrusNajmabadi
2021-08-04T19:12:45Z
2021-08-04T22:34:08Z
967cf7cf7be8478cce7cda728217eab8504f2863
d41ae79bb1a3f0deb2de2f3d67c976f795da9563
Update package references.
./src/Workspaces/CoreTestUtilities/Microsoft.CodeAnalysis.Workspaces.Test.Utilities.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk.WindowsDesktop"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis.UnitTests</RootNamespace> <TargetFrameworks>net5.0-windows7.0;netcoreapp3.1;net472</TargetFrameworks> <UseWpf>true</UseWpf> <IsShipping>false</IsShipping> <ExcludeFromSourceBuild>true</ExcludeFromSourceBuild> </PropertyGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" /> <ProjectReference Include="..\Core\MSBuild\Microsoft.CodeAnalysis.Workspaces.MSBuild.csproj" /> <ProjectReference Include="..\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Workspaces.csproj" /> <ProjectReference Include="..\Remote\ServiceHub\Microsoft.CodeAnalysis.Remote.ServiceHub.csproj" /> <ProjectReference Include="..\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Workspaces.vbproj" /> <ProjectReference Include="..\Remote\Core\Microsoft.CodeAnalysis.Remote.Workspaces.csproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.CSharp" Version="$(MicrosoftCSharpVersion)" /> <PackageReference Include="Microsoft.CodeAnalysis.CSharp.Analyzer.Testing.XUnit" Version="$(MicrosoftCodeAnalysisCSharpAnalyzerTestingXUnitVersion)" /> <PackageReference Include="Microsoft.CodeAnalysis.CSharp.CodeFix.Testing.XUnit" Version="$(MicrosoftCodeAnalysisCSharpCodeFixTestingXUnitVersion)" /> <PackageReference Include="Microsoft.CodeAnalysis.CSharp.CodeRefactoring.Testing.XUnit" Version="$(MicrosoftCodeAnalysisCSharpCodeRefactoringTestingXUnitVersion)" /> <PackageReference Include="Microsoft.CodeAnalysis.VisualBasic.Analyzer.Testing.XUnit" Version="$(MicrosoftCodeAnalysisVisualBasicAnalyzerTestingXUnitVersion)" /> <PackageReference Include="Microsoft.CodeAnalysis.VisualBasic.CodeFix.Testing.XUnit" Version="$(MicrosoftCodeAnalysisVisualBasicCodeFixTestingXUnitVersion)" /> <PackageReference Include="Microsoft.CodeAnalysis.VisualBasic.CodeRefactoring.Testing.XUnit" Version="$(MicrosoftCodeAnalysisVisualBasicCodeRefactoringTestingXUnitVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Composition" Version="$(MicrosoftVisualStudioCompositionVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Validation" Version="$(MicrosoftVisualStudioValidationVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Telemetry" Version="$(MicrosoftVisualStudioTelemetryVersion)" /> <PackageReference Include="Nerdbank.Streams" Version="$(NerdbankStreamsVersion)" /> <PackageReference Include="System.Threading.Tasks.Dataflow" Version="$(SystemThreadingTasksDataflowVersion)" /> <PackageReference Include="System.Buffers" Version="$(SystemBuffersVersion)" /> <PackageReference Include="xunit.assert" Version="$(xunitassertVersion)" /> <PackageReference Include="xunit.extensibility.core" Version="$(xunitextensibilitycoreVersion)" /> <PackageReference Include="xunit.extensibility.execution" Version="$(xunitextensibilityexecutionVersion)" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Workspaces.MSBuild.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.DiagnosticsTests.Utilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures2.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.LanguageServer.Protocol.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.Workspaces.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Workspaces.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Workspaces.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.Test.Utilities2" /> <InternalsVisibleTo Include="Roslyn.VisualStudio.Next.UnitTests" /> </ItemGroup> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk.WindowsDesktop"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis.UnitTests</RootNamespace> <TargetFrameworks>net5.0-windows7.0;netcoreapp3.1;net472</TargetFrameworks> <UseWpf>true</UseWpf> <IsShipping>false</IsShipping> <ExcludeFromSourceBuild>true</ExcludeFromSourceBuild> </PropertyGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" /> <ProjectReference Include="..\Core\MSBuild\Microsoft.CodeAnalysis.Workspaces.MSBuild.csproj" /> <ProjectReference Include="..\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Workspaces.csproj" /> <ProjectReference Include="..\Remote\ServiceHub\Microsoft.CodeAnalysis.Remote.ServiceHub.csproj" /> <ProjectReference Include="..\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Workspaces.vbproj" /> <ProjectReference Include="..\Remote\Core\Microsoft.CodeAnalysis.Remote.Workspaces.csproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.CSharp" Version="$(MicrosoftCSharpVersion)" /> <PackageReference Include="Microsoft.CodeAnalysis.CSharp.Analyzer.Testing.XUnit" Version="$(MicrosoftCodeAnalysisCSharpAnalyzerTestingXUnitVersion)" /> <PackageReference Include="Microsoft.CodeAnalysis.CSharp.CodeFix.Testing.XUnit" Version="$(MicrosoftCodeAnalysisCSharpCodeFixTestingXUnitVersion)" /> <PackageReference Include="Microsoft.CodeAnalysis.CSharp.CodeRefactoring.Testing.XUnit" Version="$(MicrosoftCodeAnalysisCSharpCodeRefactoringTestingXUnitVersion)" /> <PackageReference Include="Microsoft.CodeAnalysis.VisualBasic.Analyzer.Testing.XUnit" Version="$(MicrosoftCodeAnalysisVisualBasicAnalyzerTestingXUnitVersion)" /> <PackageReference Include="Microsoft.CodeAnalysis.VisualBasic.CodeFix.Testing.XUnit" Version="$(MicrosoftCodeAnalysisVisualBasicCodeFixTestingXUnitVersion)" /> <PackageReference Include="Microsoft.CodeAnalysis.VisualBasic.CodeRefactoring.Testing.XUnit" Version="$(MicrosoftCodeAnalysisVisualBasicCodeRefactoringTestingXUnitVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Composition" Version="$(MicrosoftVisualStudioCompositionVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Validation" Version="$(MicrosoftVisualStudioValidationVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Telemetry" Version="$(MicrosoftVisualStudioTelemetryVersion)" /> <PackageReference Include="Nerdbank.Streams" Version="$(NerdbankStreamsVersion)" /> <PackageReference Include="System.Threading.Tasks.Dataflow" Version="$(SystemThreadingTasksDataflowVersion)" /> <PackageReference Include="System.Buffers" Version="$(SystemBuffersVersion)" /> <PackageReference Include="xunit.assert" Version="$(xunitassertVersion)" /> <PackageReference Include="xunit.extensibility.core" Version="$(xunitextensibilitycoreVersion)" /> <PackageReference Include="xunit.extensibility.execution" Version="$(xunitextensibilityexecutionVersion)" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Workspaces.MSBuild.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.DiagnosticsTests.Utilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures2.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.LanguageServer.Protocol.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.Workspaces.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Workspaces.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Workspaces.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.Test.Utilities2" /> <InternalsVisibleTo Include="Roslyn.VisualStudio.Next.UnitTests" /> </ItemGroup> </Project>
-1
dotnet/roslyn
55,408
Update package references
CyrusNajmabadi
2021-08-04T19:12:45Z
2021-08-04T22:34:08Z
967cf7cf7be8478cce7cda728217eab8504f2863
d41ae79bb1a3f0deb2de2f3d67c976f795da9563
Update package references.
./src/Compilers/CSharp/Test/IOperation/Microsoft.CodeAnalysis.CSharp.IOperation.UnitTests.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis.CSharp.IOperation.UnitTests</RootNamespace> <TargetFrameworks>net5.0;net472</TargetFrameworks> </PropertyGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\..\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" /> <ProjectReference Include="..\..\..\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\..\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" /> <ProjectReference Include="..\..\..\Test\Utilities\CSharp\Microsoft.CodeAnalysis.CSharp.Test.Utilities.csproj" /> <ProjectReference Include="..\..\..\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> <ProjectReference Include="..\..\Portable\Microsoft.CodeAnalysis.CSharp.csproj" /> <ProjectReference Include="..\..\..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.CSharp" Version="$(MicrosoftCSharpVersion)" /> </ItemGroup> <ItemGroup> <Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" /> </ItemGroup> <Import Project="$(RepositoryEngineeringDir)targets\ILAsm.targets" /> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis.CSharp.IOperation.UnitTests</RootNamespace> <TargetFrameworks>net5.0;net472</TargetFrameworks> </PropertyGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\..\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" /> <ProjectReference Include="..\..\..\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\..\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" /> <ProjectReference Include="..\..\..\Test\Utilities\CSharp\Microsoft.CodeAnalysis.CSharp.Test.Utilities.csproj" /> <ProjectReference Include="..\..\..\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> <ProjectReference Include="..\..\Portable\Microsoft.CodeAnalysis.CSharp.csproj" /> <ProjectReference Include="..\..\..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.CSharp" Version="$(MicrosoftCSharpVersion)" /> </ItemGroup> <ItemGroup> <Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" /> </ItemGroup> <Import Project="$(RepositoryEngineeringDir)targets\ILAsm.targets" /> </Project>
-1
dotnet/roslyn
55,408
Update package references
CyrusNajmabadi
2021-08-04T19:12:45Z
2021-08-04T22:34:08Z
967cf7cf7be8478cce7cda728217eab8504f2863
d41ae79bb1a3f0deb2de2f3d67c976f795da9563
Update package references.
./src/Scripting/CoreTestUtilities/Microsoft.CodeAnalysis.Scripting.TestUtilities.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <TargetFramework>netstandard2.0</TargetFramework> <NoStdLib>true</NoStdLib> <IsShipping>false</IsShipping> <ExcludeFromSourceBuild>true</ExcludeFromSourceBuild> </PropertyGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" /> <ProjectReference Include="..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> <ProjectReference Include="..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" /> <ProjectReference Include="..\Core\Microsoft.CodeAnalysis.Scripting.csproj" /> <ProjectReference Include="..\CSharp\Microsoft.CodeAnalysis.CSharp.Scripting.csproj" /> <ProjectReference Include="..\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.Scripting.vbproj" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.Scripting.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.Scripting.Desktop.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Scripting.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Scripting.Desktop.UnitTests" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.CSharp" Version="$(MicrosoftCSharpVersion)" /> <PackageReference Include="Microsoft.NETCore.Platforms" Version="$(MicrosoftNETCorePlatformsVersion)" /> </ItemGroup> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <TargetFramework>netstandard2.0</TargetFramework> <NoStdLib>true</NoStdLib> <IsShipping>false</IsShipping> <ExcludeFromSourceBuild>true</ExcludeFromSourceBuild> </PropertyGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" /> <ProjectReference Include="..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> <ProjectReference Include="..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" /> <ProjectReference Include="..\Core\Microsoft.CodeAnalysis.Scripting.csproj" /> <ProjectReference Include="..\CSharp\Microsoft.CodeAnalysis.CSharp.Scripting.csproj" /> <ProjectReference Include="..\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.Scripting.vbproj" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.Scripting.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.Scripting.Desktop.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Scripting.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Scripting.Desktop.UnitTests" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.CSharp" Version="$(MicrosoftCSharpVersion)" /> <PackageReference Include="Microsoft.NETCore.Platforms" Version="$(MicrosoftNETCorePlatformsVersion)" /> </ItemGroup> </Project>
-1
dotnet/roslyn
55,408
Update package references
CyrusNajmabadi
2021-08-04T19:12:45Z
2021-08-04T22:34:08Z
967cf7cf7be8478cce7cda728217eab8504f2863
d41ae79bb1a3f0deb2de2f3d67c976f795da9563
Update package references.
./src/CodeStyle/CSharp/CodeFixes/Microsoft.CodeAnalysis.CSharp.CodeStyle.Fixes.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis.CSharp</RootNamespace> <TargetFramework>netstandard2.0</TargetFramework> <DefineConstants>$(DefineConstants),CODE_STYLE</DefineConstants> <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies> <!-- NuGet --> <IsPackable>true</IsPackable> <IsAnalyzer>true</IsAnalyzer> <NuSpecPackageId>Microsoft.CodeAnalysis.CSharp.CodeStyle</NuSpecPackageId> <PackageDescription> .NET Compiler Platform ("Roslyn") code style analyzers for C#. </PackageDescription> <TargetsForTfmSpecificContentInPackage>$(TargetsForTfmSpecificContentInPackage);_GetFilesToPackage</TargetsForTfmSpecificContentInPackage> <!-- Remove once https://github.com/NuGet/Home/issues/8583 is fixed --> <NoWarn>$(NoWarn);NU5128</NoWarn> </PropertyGroup> <Target Name="_GetFilesToPackage"> <PropertyGroup> <CodeStyleAnalyzerArtifactsBinDir>$(ArtifactsBinDir)Microsoft.CodeAnalysis.CodeStyle\$(Configuration)\$(TargetFramework)</CodeStyleAnalyzerArtifactsBinDir> <CodeStyleFixesArtifactsBinDir>$(ArtifactsBinDir)Microsoft.CodeAnalysis.CodeStyle.Fixes\$(Configuration)\$(TargetFramework)</CodeStyleFixesArtifactsBinDir> <CSharpCodeStyleAnalyzerArtifactsBinDir>$(ArtifactsBinDir)Microsoft.CodeAnalysis.CSharp.CodeStyle\$(Configuration)\$(TargetFramework)</CSharpCodeStyleAnalyzerArtifactsBinDir> <CSharpCodeStyleFixesArtifactsBinDir>$(ArtifactsBinDir)Microsoft.CodeAnalysis.CSharp.CodeStyle.Fixes\$(Configuration)\$(TargetFramework)</CSharpCodeStyleFixesArtifactsBinDir> <CSharpCodeStyleTargetsFileName>Microsoft.CodeAnalysis.CSharp.CodeStyle.targets</CSharpCodeStyleTargetsFileName> <DotNetExecutable Condition="'$(OS)' == 'Windows_NT'">$(DotNetRoot)dotnet.exe</DotNetExecutable> <DotNetExecutable Condition="'$(DotNetExecutable)' == ''">$(DotNetRoot)dotnet</DotNetExecutable> </PropertyGroup> <Exec Command='"$(DotNetExecutable)" "$(ArtifactsBinDir)CodeStyleConfigFileGenerator\$(Configuration)\netcoreapp3.1\CodeStyleConfigFileGenerator.dll" "CSharp" "$(CSharpCodeStyleFixesArtifactsBinDir)" "$(CSharpCodeStyleTargetsFileName)" "$(CodeStyleAnalyzerArtifactsBinDir)\Microsoft.CodeAnalysis.CodeStyle.dll;$(CSharpCodeStyleAnalyzerArtifactsBinDir)\Microsoft.CodeAnalysis.CSharp.CodeStyle.dll"' /> <ItemGroup> <_File Include="$(CSharpCodeStyleAnalyzerArtifactsBinDir)\Microsoft.CodeAnalysis.CSharp.CodeStyle.dll" TargetDir="analyzers/dotnet/cs" /> <_File Include="$(CSharpCodeStyleFixesArtifactsBinDir)\Microsoft.CodeAnalysis.CSharp.CodeStyle.Fixes.dll" TargetDir="analyzers/dotnet/cs" /> <_File Include="$(CodeStyleAnalyzerArtifactsBinDir)\Microsoft.CodeAnalysis.CodeStyle.dll" TargetDir="analyzers/dotnet/cs" /> <_File Include="$(CodeStyleFixesArtifactsBinDir)\Microsoft.CodeAnalysis.CodeStyle.Fixes.dll" TargetDir="analyzers/dotnet/cs" /> <_File Include="$(CSharpCodeStyleAnalyzerArtifactsBinDir)\**\Microsoft.CodeAnalysis.CSharp.CodeStyle.resources.dll" TargetDir="analyzers/dotnet/cs" /> <_File Include="$(CSharpCodeStyleFixesArtifactsBinDir)\**\Microsoft.CodeAnalysis.CSharp.CodeStyle.Fixes.resources.dll" TargetDir="analyzers/dotnet/cs" /> <_File Include="$(CodeStyleAnalyzerArtifactsBinDir)\**\Microsoft.CodeAnalysis.CodeStyle.resources.dll" TargetDir="analyzers/dotnet/cs" /> <_File Include="$(CodeStyleFixesArtifactsBinDir)\**\Microsoft.CodeAnalysis.CodeStyle.Fixes.resources.dll" TargetDir="analyzers/dotnet/cs" /> <_File Include="$(CSharpCodeStyleFixesArtifactsBinDir)\$(CSharpCodeStyleTargetsFileName)" TargetDir="build" /> <_File Include="$(CSharpCodeStyleFixesArtifactsBinDir)\config\**\*.*" TargetDir="build/config" /> <_File Include="$(MSBuildProjectDirectory)\build\**\*.*" TargetDir="build" /> <TfmSpecificPackageFile Include="@(_File)" PackagePath="%(_File.TargetDir)/%(_File.RecursiveDir)%(_File.FileName)%(_File.Extension)" /> </ItemGroup> </Target> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\..\Workspaces\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Workspaces.csproj" /> <ProjectReference Include="..\..\Core\Analyzers\Microsoft.CodeAnalysis.CodeStyle.csproj" /> <ProjectReference Include="..\..\Core\CodeFixes\Microsoft.CodeAnalysis.CodeStyle.Fixes.csproj" /> <ProjectReference Include="..\Analyzers\Microsoft.CodeAnalysis.CSharp.CodeStyle.csproj" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.CodeStyle.UnitTests" /> </ItemGroup> <ItemGroup> <EmbeddedResource Update="CSharpCodeStyleFixesResources.resx" GenerateSource="true" /> </ItemGroup> <ItemGroup> <PublicAPI Include="PublicAPI.Shipped.txt" /> <PublicAPI Include="PublicAPI.Unshipped.txt" /> </ItemGroup> <ItemGroup> <None Include="build\Microsoft.CodeAnalysis.CSharp.CodeStyle.props" /> </ItemGroup> <Import Project="..\..\..\Workspaces\SharedUtilitiesAndExtensions\Workspace\CSharp\CSharpWorkspaceExtensions.projitems" Label="Shared" /> <Import Project="..\..\..\Analyzers\CSharp\CodeFixes\CSharpCodeFixes.projitems" Label="Shared" /> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis.CSharp</RootNamespace> <TargetFramework>netstandard2.0</TargetFramework> <DefineConstants>$(DefineConstants),CODE_STYLE</DefineConstants> <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies> <!-- NuGet --> <IsPackable>true</IsPackable> <IsAnalyzer>true</IsAnalyzer> <NuSpecPackageId>Microsoft.CodeAnalysis.CSharp.CodeStyle</NuSpecPackageId> <PackageDescription> .NET Compiler Platform ("Roslyn") code style analyzers for C#. </PackageDescription> <TargetsForTfmSpecificContentInPackage>$(TargetsForTfmSpecificContentInPackage);_GetFilesToPackage</TargetsForTfmSpecificContentInPackage> <!-- Remove once https://github.com/NuGet/Home/issues/8583 is fixed --> <NoWarn>$(NoWarn);NU5128</NoWarn> </PropertyGroup> <Target Name="_GetFilesToPackage"> <PropertyGroup> <CodeStyleAnalyzerArtifactsBinDir>$(ArtifactsBinDir)Microsoft.CodeAnalysis.CodeStyle\$(Configuration)\$(TargetFramework)</CodeStyleAnalyzerArtifactsBinDir> <CodeStyleFixesArtifactsBinDir>$(ArtifactsBinDir)Microsoft.CodeAnalysis.CodeStyle.Fixes\$(Configuration)\$(TargetFramework)</CodeStyleFixesArtifactsBinDir> <CSharpCodeStyleAnalyzerArtifactsBinDir>$(ArtifactsBinDir)Microsoft.CodeAnalysis.CSharp.CodeStyle\$(Configuration)\$(TargetFramework)</CSharpCodeStyleAnalyzerArtifactsBinDir> <CSharpCodeStyleFixesArtifactsBinDir>$(ArtifactsBinDir)Microsoft.CodeAnalysis.CSharp.CodeStyle.Fixes\$(Configuration)\$(TargetFramework)</CSharpCodeStyleFixesArtifactsBinDir> <CSharpCodeStyleTargetsFileName>Microsoft.CodeAnalysis.CSharp.CodeStyle.targets</CSharpCodeStyleTargetsFileName> <DotNetExecutable Condition="'$(OS)' == 'Windows_NT'">$(DotNetRoot)dotnet.exe</DotNetExecutable> <DotNetExecutable Condition="'$(DotNetExecutable)' == ''">$(DotNetRoot)dotnet</DotNetExecutable> </PropertyGroup> <Exec Command='"$(DotNetExecutable)" "$(ArtifactsBinDir)CodeStyleConfigFileGenerator\$(Configuration)\netcoreapp3.1\CodeStyleConfigFileGenerator.dll" "CSharp" "$(CSharpCodeStyleFixesArtifactsBinDir)" "$(CSharpCodeStyleTargetsFileName)" "$(CodeStyleAnalyzerArtifactsBinDir)\Microsoft.CodeAnalysis.CodeStyle.dll;$(CSharpCodeStyleAnalyzerArtifactsBinDir)\Microsoft.CodeAnalysis.CSharp.CodeStyle.dll"' /> <ItemGroup> <_File Include="$(CSharpCodeStyleAnalyzerArtifactsBinDir)\Microsoft.CodeAnalysis.CSharp.CodeStyle.dll" TargetDir="analyzers/dotnet/cs" /> <_File Include="$(CSharpCodeStyleFixesArtifactsBinDir)\Microsoft.CodeAnalysis.CSharp.CodeStyle.Fixes.dll" TargetDir="analyzers/dotnet/cs" /> <_File Include="$(CodeStyleAnalyzerArtifactsBinDir)\Microsoft.CodeAnalysis.CodeStyle.dll" TargetDir="analyzers/dotnet/cs" /> <_File Include="$(CodeStyleFixesArtifactsBinDir)\Microsoft.CodeAnalysis.CodeStyle.Fixes.dll" TargetDir="analyzers/dotnet/cs" /> <_File Include="$(CSharpCodeStyleAnalyzerArtifactsBinDir)\**\Microsoft.CodeAnalysis.CSharp.CodeStyle.resources.dll" TargetDir="analyzers/dotnet/cs" /> <_File Include="$(CSharpCodeStyleFixesArtifactsBinDir)\**\Microsoft.CodeAnalysis.CSharp.CodeStyle.Fixes.resources.dll" TargetDir="analyzers/dotnet/cs" /> <_File Include="$(CodeStyleAnalyzerArtifactsBinDir)\**\Microsoft.CodeAnalysis.CodeStyle.resources.dll" TargetDir="analyzers/dotnet/cs" /> <_File Include="$(CodeStyleFixesArtifactsBinDir)\**\Microsoft.CodeAnalysis.CodeStyle.Fixes.resources.dll" TargetDir="analyzers/dotnet/cs" /> <_File Include="$(CSharpCodeStyleFixesArtifactsBinDir)\$(CSharpCodeStyleTargetsFileName)" TargetDir="build" /> <_File Include="$(CSharpCodeStyleFixesArtifactsBinDir)\config\**\*.*" TargetDir="build/config" /> <_File Include="$(MSBuildProjectDirectory)\build\**\*.*" TargetDir="build" /> <TfmSpecificPackageFile Include="@(_File)" PackagePath="%(_File.TargetDir)/%(_File.RecursiveDir)%(_File.FileName)%(_File.Extension)" /> </ItemGroup> </Target> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\..\Workspaces\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Workspaces.csproj" /> <ProjectReference Include="..\..\Core\Analyzers\Microsoft.CodeAnalysis.CodeStyle.csproj" /> <ProjectReference Include="..\..\Core\CodeFixes\Microsoft.CodeAnalysis.CodeStyle.Fixes.csproj" /> <ProjectReference Include="..\Analyzers\Microsoft.CodeAnalysis.CSharp.CodeStyle.csproj" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.CodeStyle.UnitTests" /> </ItemGroup> <ItemGroup> <EmbeddedResource Update="CSharpCodeStyleFixesResources.resx" GenerateSource="true" /> </ItemGroup> <ItemGroup> <PublicAPI Include="PublicAPI.Shipped.txt" /> <PublicAPI Include="PublicAPI.Unshipped.txt" /> </ItemGroup> <ItemGroup> <None Include="build\Microsoft.CodeAnalysis.CSharp.CodeStyle.props" /> </ItemGroup> <Import Project="..\..\..\Workspaces\SharedUtilitiesAndExtensions\Workspace\CSharp\CSharpWorkspaceExtensions.projitems" Label="Shared" /> <Import Project="..\..\..\Analyzers\CSharp\CodeFixes\CSharpCodeFixes.projitems" Label="Shared" /> </Project>
-1
dotnet/roslyn
55,408
Update package references
CyrusNajmabadi
2021-08-04T19:12:45Z
2021-08-04T22:34:08Z
967cf7cf7be8478cce7cda728217eab8504f2863
d41ae79bb1a3f0deb2de2f3d67c976f795da9563
Update package references.
./src/Test/Diagnostics/Roslyn.Hosting.Diagnostics.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk.WindowsDesktop"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Roslyn.Hosting.Diagnostics</RootNamespace> <TargetFramework>net472</TargetFramework> <UseWpf>true</UseWpf> </PropertyGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\EditorFeatures\TestUtilities\Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities.csproj" /> <ProjectReference Include="..\..\Workspaces\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" /> <ProjectReference Include="..\..\EditorFeatures\Core\Microsoft.CodeAnalysis.EditorFeatures.csproj" /> <ProjectReference Include="..\..\Features\Core\Portable\Microsoft.CodeAnalysis.Features.csproj" /> <ProjectReference Include="..\..\Workspaces\Remote\Core\Microsoft.CodeAnalysis.Remote.Workspaces.csproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.VisualStudio.Imaging.Interop.14.0.DesignTime" Version="$(MicrosoftVisualStudioImagingInterop140DesignTimeVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Utilities" Version="$(MicrosoftVisualStudioUtilitiesVersion)" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Microsoft.VisualStudio.IntegrationTest.Utilities" /> <InternalsVisibleTo Include="Roslyn.VisualStudio.DiagnosticsWindow" /> </ItemGroup> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk.WindowsDesktop"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Roslyn.Hosting.Diagnostics</RootNamespace> <TargetFramework>net472</TargetFramework> <UseWpf>true</UseWpf> </PropertyGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\EditorFeatures\TestUtilities\Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities.csproj" /> <ProjectReference Include="..\..\Workspaces\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" /> <ProjectReference Include="..\..\EditorFeatures\Core\Microsoft.CodeAnalysis.EditorFeatures.csproj" /> <ProjectReference Include="..\..\Features\Core\Portable\Microsoft.CodeAnalysis.Features.csproj" /> <ProjectReference Include="..\..\Workspaces\Remote\Core\Microsoft.CodeAnalysis.Remote.Workspaces.csproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.VisualStudio.Imaging.Interop.14.0.DesignTime" Version="$(MicrosoftVisualStudioImagingInterop140DesignTimeVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Utilities" Version="$(MicrosoftVisualStudioUtilitiesVersion)" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Microsoft.VisualStudio.IntegrationTest.Utilities" /> <InternalsVisibleTo Include="Roslyn.VisualStudio.DiagnosticsWindow" /> </ItemGroup> </Project>
-1
dotnet/roslyn
55,408
Update package references
CyrusNajmabadi
2021-08-04T19:12:45Z
2021-08-04T22:34:08Z
967cf7cf7be8478cce7cda728217eab8504f2863
d41ae79bb1a3f0deb2de2f3d67c976f795da9563
Update package references.
./src/NuGet/Microsoft.NETCore.Compilers/Microsoft.NETCore.Compilers.Package.csproj
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netcoreapp3.1</TargetFramework> <IsPackable>true</IsPackable> <NuspecPackageId>Microsoft.NETCore.Compilers</NuspecPackageId> <IncludeBuildOutput>false</IncludeBuildOutput> <DevelopmentDependency>true</DevelopmentDependency> <PackageDescription> Note: This package is deprecated. Please use Microsoft.Net.Compilers.Toolset instead CoreCLR-compatible versions of the C# and VB compilers for use in MSBuild. </PackageDescription> <TargetsForTfmSpecificContentInPackage>$(TargetsForTfmSpecificContentInPackage);_GetFilesToPackage</TargetsForTfmSpecificContentInPackage> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\..\Compilers\CSharp\csc\csc.csproj"/> <ProjectReference Include="..\..\Compilers\VisualBasic\vbc\vbc.csproj"/> <ProjectReference Include="..\..\Interactive\csi\csi.csproj"/> <ProjectReference Include="..\..\Compilers\Core\MSBuildTask\Microsoft.Build.Tasks.CodeAnalysis.csproj"/> <ProjectReference Include="..\..\Compilers\Server\VBCSCompiler\VBCSCompiler.csproj"/> </ItemGroup> <ItemGroup> <ProjectReference Update="@(ProjectReference)" Targets="Publish" ReferenceOutputAssembly="false" SkipGetTargetFrameworkProperties="true" SetTargetFramework="TargetFramework=$(TargetFramework)" /> </ItemGroup> <Target Name="_GetFilesToPackage" DependsOnTargets="InitializeCoreClrCompilerArtifacts"> <ItemGroup> <_File Include="@(CoreClrCompilerBuildArtifact)" TargetDir="build"/> <_File Include="@(CoreClrCompilerToolsArtifact)" TargetDir="tools"/> <_File Include="@(CoreClrCompilerBinArtifact)" TargetDir="tools\bincore"/> <_File Include="@(CoreClrCompilerBinRuntimesArtifact)" TargetDir="tools\bincore\runtimes"/> <_File Include="$(MSBuildProjectDirectory)\build\**\*.*" TargetDir="build" /> <TfmSpecificPackageFile Include="@(_File)" PackagePath="%(_File.TargetDir)\%(_File.RecursiveDir)%(_File.FileName)%(_File.Extension)"/> </ItemGroup> </Target> <Import Project="..\Microsoft.Net.Compilers.Toolset\CoreClrCompilerArtifacts.targets"/> </Project>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netcoreapp3.1</TargetFramework> <IsPackable>true</IsPackable> <NuspecPackageId>Microsoft.NETCore.Compilers</NuspecPackageId> <IncludeBuildOutput>false</IncludeBuildOutput> <DevelopmentDependency>true</DevelopmentDependency> <PackageDescription> Note: This package is deprecated. Please use Microsoft.Net.Compilers.Toolset instead CoreCLR-compatible versions of the C# and VB compilers for use in MSBuild. </PackageDescription> <TargetsForTfmSpecificContentInPackage>$(TargetsForTfmSpecificContentInPackage);_GetFilesToPackage</TargetsForTfmSpecificContentInPackage> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\..\Compilers\CSharp\csc\csc.csproj"/> <ProjectReference Include="..\..\Compilers\VisualBasic\vbc\vbc.csproj"/> <ProjectReference Include="..\..\Interactive\csi\csi.csproj"/> <ProjectReference Include="..\..\Compilers\Core\MSBuildTask\Microsoft.Build.Tasks.CodeAnalysis.csproj"/> <ProjectReference Include="..\..\Compilers\Server\VBCSCompiler\VBCSCompiler.csproj"/> </ItemGroup> <ItemGroup> <ProjectReference Update="@(ProjectReference)" Targets="Publish" ReferenceOutputAssembly="false" SkipGetTargetFrameworkProperties="true" SetTargetFramework="TargetFramework=$(TargetFramework)" /> </ItemGroup> <Target Name="_GetFilesToPackage" DependsOnTargets="InitializeCoreClrCompilerArtifacts"> <ItemGroup> <_File Include="@(CoreClrCompilerBuildArtifact)" TargetDir="build"/> <_File Include="@(CoreClrCompilerToolsArtifact)" TargetDir="tools"/> <_File Include="@(CoreClrCompilerBinArtifact)" TargetDir="tools\bincore"/> <_File Include="@(CoreClrCompilerBinRuntimesArtifact)" TargetDir="tools\bincore\runtimes"/> <_File Include="$(MSBuildProjectDirectory)\build\**\*.*" TargetDir="build" /> <TfmSpecificPackageFile Include="@(_File)" PackagePath="%(_File.TargetDir)\%(_File.RecursiveDir)%(_File.FileName)%(_File.Extension)"/> </ItemGroup> </Target> <Import Project="..\Microsoft.Net.Compilers.Toolset\CoreClrCompilerArtifacts.targets"/> </Project>
-1
dotnet/roslyn
55,408
Update package references
CyrusNajmabadi
2021-08-04T19:12:45Z
2021-08-04T22:34:08Z
967cf7cf7be8478cce7cda728217eab8504f2863
d41ae79bb1a3f0deb2de2f3d67c976f795da9563
Update package references.
./src/EditorFeatures/Test/Microsoft.CodeAnalysis.EditorFeatures.UnitTests.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk.WindowsDesktop"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis.Editor.UnitTests</RootNamespace> <TargetFramework>net472</TargetFramework> <UseWpf>true</UseWpf> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> </PropertyGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" /> <ProjectReference Include="..\..\Compilers\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" /> <ProjectReference Include="..\..\Compilers\Test\Utilities\CSharp\Microsoft.CodeAnalysis.CSharp.Test.Utilities.csproj" /> <ProjectReference Include="..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> <ProjectReference Include="..\..\Features\LanguageServer\Protocol\Microsoft.CodeAnalysis.LanguageServer.Protocol.csproj" /> <ProjectReference Include="..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" /> <ProjectReference Include="..\..\Interactive\Host\Microsoft.CodeAnalysis.InteractiveHost.csproj" /> <ProjectReference Include="..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" /> <ProjectReference Include="..\..\Features\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Features.vbproj" /> <ProjectReference Include="..\..\Workspaces\CoreTestUtilities\Microsoft.CodeAnalysis.Workspaces.Test.Utilities.csproj" /> <ProjectReference Include="..\..\Workspaces\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj"> <Aliases>global,WORKSPACES</Aliases> </ProjectReference> <ProjectReference Include="..\..\Features\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Features.csproj" /> <ProjectReference Include="..\..\Workspaces\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Workspaces.csproj" /> <ProjectReference Include="..\..\Features\Core\Portable\Microsoft.CodeAnalysis.Features.csproj" /> <ProjectReference Include="..\..\EditorFeatures\Text\Microsoft.CodeAnalysis.EditorFeatures.Text.csproj" /> <ProjectReference Include="..\..\Workspaces\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Workspaces.vbproj" /> <ProjectReference Include="..\..\EditorFeatures\CSharp\Microsoft.CodeAnalysis.CSharp.EditorFeatures.csproj" /> <ProjectReference Include="..\..\EditorFeatures\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.vbproj" /> <ProjectReference Include="..\..\EditorFeatures\Core\Microsoft.CodeAnalysis.EditorFeatures.csproj" /> <ProjectReference Include="..\..\EditorFeatures\Core.Wpf\Microsoft.CodeAnalysis.EditorFeatures.Wpf.csproj" /> <ProjectReference Include="..\..\Scripting\Core\Microsoft.CodeAnalysis.Scripting.csproj" /> <ProjectReference Include="..\DiagnosticsTestUtilities\Microsoft.CodeAnalysis.EditorFeatures.DiagnosticsTests.Utilities.csproj" /> <ProjectReference Include="..\TestUtilities\Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities.csproj" /> <ProjectReference Include="..\..\Scripting\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.Scripting.vbproj" /> <ProjectReference Include="..\..\Scripting\CSharp\Microsoft.CodeAnalysis.CSharp.Scripting.csproj" /> <ProjectReference Include="..\..\Workspaces\Remote\Core\Microsoft.CodeAnalysis.Remote.Workspaces.csproj" /> <ProjectReference Include="..\..\Workspaces\Remote\ServiceHub\Microsoft.CodeAnalysis.Remote.ServiceHub.csproj" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures2.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests" /> </ItemGroup> <ItemGroup> <PackageReference Include="BasicUndo" Version="$(BasicUndoVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Composition" Version="$(MicrosoftVisualStudioCompositionVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Platform.VSEditor" Version="$(MicrosoftVisualStudioPlatformVSEditorVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Imaging.Interop.14.0.DesignTime" Version="$(MicrosoftVisualStudioImagingInterop140DesignTimeVersion)" /> <PackageReference Include="Microsoft.VisualStudio.InteractiveWindow" Version="$(MicrosoftVisualStudioInteractiveWindowVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Interop" Version="$(MicrosoftVisualStudioInteropVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Language.Intellisense" Version="$(MicrosoftVisualStudioLanguageIntellisenseVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Language.CallHierarchy" Version="$(MicrosoftVisualStudioLanguageCallHierarchyVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Language.NavigateTo.Interfaces" Version="$(MicrosoftVisualStudioLanguageNavigateToInterfacesVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Language.StandardClassification" Version="$(MicrosoftVisualStudioLanguageStandardClassificationVersion)" /> <!-- Microsoft.VisualStudio.Platform.VSEditor references Microsoft.VisualStudio.Text.Internal since it's needed at runtime; we want to ensure we are using it _only_ for runtime dependencies and not anything compile time --> <PackageReference Include="Microsoft.VisualStudio.Text.Internal" Version="$(MicrosoftVisualStudioTextInternalVersion)" IncludeAssets="runtime" /> <PackageReference Include="Microsoft.VisualStudio.Text.UI" Version="$(MicrosoftVisualStudioTextUIVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Text.UI.Wpf" Version="$(MicrosoftVisualStudioTextUIWpfVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Threading" Version="$(MicrosoftVisualStudioThreadingVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Utilities" Version="$(MicrosoftVisualStudioUtilitiesVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Validation" Version="$(MicrosoftVisualStudioValidationVersion)" /> </ItemGroup> <ItemGroup> <Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" /> </ItemGroup> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk.WindowsDesktop"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis.Editor.UnitTests</RootNamespace> <TargetFramework>net472</TargetFramework> <UseWpf>true</UseWpf> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> </PropertyGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" /> <ProjectReference Include="..\..\Compilers\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" /> <ProjectReference Include="..\..\Compilers\Test\Utilities\CSharp\Microsoft.CodeAnalysis.CSharp.Test.Utilities.csproj" /> <ProjectReference Include="..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> <ProjectReference Include="..\..\Features\LanguageServer\Protocol\Microsoft.CodeAnalysis.LanguageServer.Protocol.csproj" /> <ProjectReference Include="..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" /> <ProjectReference Include="..\..\Interactive\Host\Microsoft.CodeAnalysis.InteractiveHost.csproj" /> <ProjectReference Include="..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" /> <ProjectReference Include="..\..\Features\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Features.vbproj" /> <ProjectReference Include="..\..\Workspaces\CoreTestUtilities\Microsoft.CodeAnalysis.Workspaces.Test.Utilities.csproj" /> <ProjectReference Include="..\..\Workspaces\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj"> <Aliases>global,WORKSPACES</Aliases> </ProjectReference> <ProjectReference Include="..\..\Features\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Features.csproj" /> <ProjectReference Include="..\..\Workspaces\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Workspaces.csproj" /> <ProjectReference Include="..\..\Features\Core\Portable\Microsoft.CodeAnalysis.Features.csproj" /> <ProjectReference Include="..\..\EditorFeatures\Text\Microsoft.CodeAnalysis.EditorFeatures.Text.csproj" /> <ProjectReference Include="..\..\Workspaces\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Workspaces.vbproj" /> <ProjectReference Include="..\..\EditorFeatures\CSharp\Microsoft.CodeAnalysis.CSharp.EditorFeatures.csproj" /> <ProjectReference Include="..\..\EditorFeatures\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.vbproj" /> <ProjectReference Include="..\..\EditorFeatures\Core\Microsoft.CodeAnalysis.EditorFeatures.csproj" /> <ProjectReference Include="..\..\EditorFeatures\Core.Wpf\Microsoft.CodeAnalysis.EditorFeatures.Wpf.csproj" /> <ProjectReference Include="..\..\Scripting\Core\Microsoft.CodeAnalysis.Scripting.csproj" /> <ProjectReference Include="..\DiagnosticsTestUtilities\Microsoft.CodeAnalysis.EditorFeatures.DiagnosticsTests.Utilities.csproj" /> <ProjectReference Include="..\TestUtilities\Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities.csproj" /> <ProjectReference Include="..\..\Scripting\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.Scripting.vbproj" /> <ProjectReference Include="..\..\Scripting\CSharp\Microsoft.CodeAnalysis.CSharp.Scripting.csproj" /> <ProjectReference Include="..\..\Workspaces\Remote\Core\Microsoft.CodeAnalysis.Remote.Workspaces.csproj" /> <ProjectReference Include="..\..\Workspaces\Remote\ServiceHub\Microsoft.CodeAnalysis.Remote.ServiceHub.csproj" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures2.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests" /> </ItemGroup> <ItemGroup> <PackageReference Include="BasicUndo" Version="$(BasicUndoVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Composition" Version="$(MicrosoftVisualStudioCompositionVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Platform.VSEditor" Version="$(MicrosoftVisualStudioPlatformVSEditorVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Imaging.Interop.14.0.DesignTime" Version="$(MicrosoftVisualStudioImagingInterop140DesignTimeVersion)" /> <PackageReference Include="Microsoft.VisualStudio.InteractiveWindow" Version="$(MicrosoftVisualStudioInteractiveWindowVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Interop" Version="$(MicrosoftVisualStudioInteropVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Language.Intellisense" Version="$(MicrosoftVisualStudioLanguageIntellisenseVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Language.CallHierarchy" Version="$(MicrosoftVisualStudioLanguageCallHierarchyVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Language.NavigateTo.Interfaces" Version="$(MicrosoftVisualStudioLanguageNavigateToInterfacesVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Language.StandardClassification" Version="$(MicrosoftVisualStudioLanguageStandardClassificationVersion)" /> <!-- Microsoft.VisualStudio.Platform.VSEditor references Microsoft.VisualStudio.Text.Internal since it's needed at runtime; we want to ensure we are using it _only_ for runtime dependencies and not anything compile time --> <PackageReference Include="Microsoft.VisualStudio.Text.Internal" Version="$(MicrosoftVisualStudioTextInternalVersion)" IncludeAssets="runtime" /> <PackageReference Include="Microsoft.VisualStudio.Text.UI" Version="$(MicrosoftVisualStudioTextUIVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Text.UI.Wpf" Version="$(MicrosoftVisualStudioTextUIWpfVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Threading" Version="$(MicrosoftVisualStudioThreadingVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Utilities" Version="$(MicrosoftVisualStudioUtilitiesVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Validation" Version="$(MicrosoftVisualStudioValidationVersion)" /> </ItemGroup> <ItemGroup> <Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" /> </ItemGroup> </Project>
-1
dotnet/roslyn
55,408
Update package references
CyrusNajmabadi
2021-08-04T19:12:45Z
2021-08-04T22:34:08Z
967cf7cf7be8478cce7cda728217eab8504f2863
d41ae79bb1a3f0deb2de2f3d67c976f795da9563
Update package references.
./src/Compilers/CSharp/Portable/Symbols/MutableTypeMap.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Utility class for substituting actual type arguments for formal generic type parameters. /// </summary> internal sealed class MutableTypeMap : AbstractTypeParameterMap { internal MutableTypeMap() : base(new SmallDictionary<TypeParameterSymbol, TypeWithAnnotations>()) { } internal void Add(TypeParameterSymbol key, TypeWithAnnotations value) { this.Mapping.Add(key, value); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Utility class for substituting actual type arguments for formal generic type parameters. /// </summary> internal sealed class MutableTypeMap : AbstractTypeParameterMap { internal MutableTypeMap() : base(new SmallDictionary<TypeParameterSymbol, TypeWithAnnotations>()) { } internal void Add(TypeParameterSymbol key, TypeWithAnnotations value) { this.Mapping.Add(key, value); } } }
-1